babylon.max.js 3.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. var absX = Math.abs(this.x);
  1403. var absY = Math.abs(this.y);
  1404. if (absX !== absY) {
  1405. return true;
  1406. }
  1407. var absZ = Math.abs(this.z);
  1408. if (absX !== absZ) {
  1409. return true;
  1410. }
  1411. if (absY !== absZ) {
  1412. return true;
  1413. }
  1414. return false;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. // Properties
  1420. /**
  1421. * Returns the length of the Vector3 (float).
  1422. */
  1423. Vector3.prototype.length = function () {
  1424. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1425. };
  1426. /**
  1427. * Returns the squared length of the Vector3 (float).
  1428. */
  1429. Vector3.prototype.lengthSquared = function () {
  1430. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1431. };
  1432. // Methods
  1433. /**
  1434. * Normalize the current Vector3.
  1435. * Returns the updated Vector3.
  1436. */
  1437. Vector3.prototype.normalize = function () {
  1438. var len = this.length();
  1439. if (len === 0 || len === 1.0)
  1440. return this;
  1441. var num = 1.0 / len;
  1442. this.x *= num;
  1443. this.y *= num;
  1444. this.z *= num;
  1445. return this;
  1446. };
  1447. /**
  1448. * Returns a new Vector3 copied from the current Vector3.
  1449. */
  1450. Vector3.prototype.clone = function () {
  1451. return new Vector3(this.x, this.y, this.z);
  1452. };
  1453. /**
  1454. * Copies the passed vector coordinates to the current Vector3 ones.
  1455. * Returns the updated Vector3.
  1456. */
  1457. Vector3.prototype.copyFrom = function (source) {
  1458. this.x = source.x;
  1459. this.y = source.y;
  1460. this.z = source.z;
  1461. return this;
  1462. };
  1463. /**
  1464. * Copies the passed floats to the current Vector3 coordinates.
  1465. * Returns the updated Vector3.
  1466. */
  1467. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1468. this.x = x;
  1469. this.y = y;
  1470. this.z = z;
  1471. return this;
  1472. };
  1473. /**
  1474. * Copies the passed floats to the current Vector3 coordinates.
  1475. * Returns the updated Vector3.
  1476. */
  1477. Vector3.prototype.set = function (x, y, z) {
  1478. return this.copyFromFloats(x, y, z);
  1479. };
  1480. // Statics
  1481. /**
  1482. *
  1483. */
  1484. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1485. var d0 = Vector3.Dot(vector0, axis) - size;
  1486. var d1 = Vector3.Dot(vector1, axis) - size;
  1487. var s = d0 / (d0 - d1);
  1488. return s;
  1489. };
  1490. /**
  1491. * Returns a new Vector3 set from the index "offset" of the passed array.
  1492. */
  1493. Vector3.FromArray = function (array, offset) {
  1494. if (!offset) {
  1495. offset = 0;
  1496. }
  1497. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1498. };
  1499. /**
  1500. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1501. * This function is deprecated. Use FromArray instead.
  1502. */
  1503. Vector3.FromFloatArray = function (array, offset) {
  1504. return Vector3.FromArray(array, offset);
  1505. };
  1506. /**
  1507. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1508. */
  1509. Vector3.FromArrayToRef = function (array, offset, result) {
  1510. result.x = array[offset];
  1511. result.y = array[offset + 1];
  1512. result.z = array[offset + 2];
  1513. };
  1514. /**
  1515. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1516. * This function is deprecated. Use FromArrayToRef instead.
  1517. */
  1518. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1519. return Vector3.FromArrayToRef(array, offset, result);
  1520. };
  1521. /**
  1522. * Sets the passed vector "result" with the passed floats.
  1523. */
  1524. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1525. result.x = x;
  1526. result.y = y;
  1527. result.z = z;
  1528. };
  1529. /**
  1530. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1531. */
  1532. Vector3.Zero = function () {
  1533. return new Vector3(0.0, 0.0, 0.0);
  1534. };
  1535. /**
  1536. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1537. */
  1538. Vector3.One = function () {
  1539. return new Vector3(1.0, 1.0, 1.0);
  1540. };
  1541. /**
  1542. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1543. */
  1544. Vector3.Up = function () {
  1545. return new Vector3(0.0, 1.0, 0.0);
  1546. };
  1547. /**
  1548. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1549. */
  1550. Vector3.Forward = function () {
  1551. return new Vector3(0.0, 0.0, 1.0);
  1552. };
  1553. /**
  1554. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1555. */
  1556. Vector3.Right = function () {
  1557. return new Vector3(1.0, 0.0, 0.0);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1561. */
  1562. Vector3.Left = function () {
  1563. return new Vector3(-1.0, 0.0, 0.0);
  1564. };
  1565. /**
  1566. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1567. * This method computes tranformed coordinates only, not transformed direction vectors.
  1568. */
  1569. Vector3.TransformCoordinates = function (vector, transformation) {
  1570. var result = Vector3.Zero();
  1571. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1572. return result;
  1573. };
  1574. /**
  1575. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1576. * This method computes tranformed coordinates only, not transformed direction vectors.
  1577. */
  1578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1583. result.x = x / w;
  1584. result.y = y / w;
  1585. result.z = z / w;
  1586. };
  1587. /**
  1588. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1589. * This method computes tranformed coordinates only, not transformed direction vectors.
  1590. */
  1591. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1592. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1593. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1594. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1595. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1596. result.x = rx / rw;
  1597. result.y = ry / rw;
  1598. result.z = rz / rw;
  1599. };
  1600. /**
  1601. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1602. * This methods computes transformed normalized direction vectors only.
  1603. */
  1604. Vector3.TransformNormal = function (vector, transformation) {
  1605. var result = Vector3.Zero();
  1606. Vector3.TransformNormalToRef(vector, transformation, result);
  1607. return result;
  1608. };
  1609. /**
  1610. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1611. * This methods computes transformed normalized direction vectors only.
  1612. */
  1613. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1614. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1615. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1616. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1617. result.x = x;
  1618. result.y = y;
  1619. result.z = z;
  1620. };
  1621. /**
  1622. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1623. * This methods computes transformed normalized direction vectors only.
  1624. */
  1625. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1626. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1627. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1628. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1629. };
  1630. /**
  1631. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1632. */
  1633. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1634. var squared = amount * amount;
  1635. var cubed = amount * squared;
  1636. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1637. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1638. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1639. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1640. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1641. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1642. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1643. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1644. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1645. return new Vector3(x, y, z);
  1646. };
  1647. /**
  1648. * 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".
  1649. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1650. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1651. */
  1652. Vector3.Clamp = function (value, min, max) {
  1653. var x = value.x;
  1654. x = (x > max.x) ? max.x : x;
  1655. x = (x < min.x) ? min.x : x;
  1656. var y = value.y;
  1657. y = (y > max.y) ? max.y : y;
  1658. y = (y < min.y) ? min.y : y;
  1659. var z = value.z;
  1660. z = (z > max.z) ? max.z : z;
  1661. z = (z < min.z) ? min.z : z;
  1662. return new Vector3(x, y, z);
  1663. };
  1664. /**
  1665. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1666. */
  1667. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1668. var squared = amount * amount;
  1669. var cubed = amount * squared;
  1670. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1671. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1672. var part3 = (cubed - (2.0 * squared)) + amount;
  1673. var part4 = cubed - squared;
  1674. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1675. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1676. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1677. return new Vector3(x, y, z);
  1678. };
  1679. /**
  1680. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1681. */
  1682. Vector3.Lerp = function (start, end, amount) {
  1683. var result = new Vector3(0, 0, 0);
  1684. Vector3.LerpToRef(start, end, amount, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1689. */
  1690. Vector3.LerpToRef = function (start, end, amount, result) {
  1691. result.x = start.x + ((end.x - start.x) * amount);
  1692. result.y = start.y + ((end.y - start.y) * amount);
  1693. result.z = start.z + ((end.z - start.z) * amount);
  1694. };
  1695. /**
  1696. * Returns the dot product (float) between the vectors "left" and "right".
  1697. */
  1698. Vector3.Dot = function (left, right) {
  1699. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1700. };
  1701. /**
  1702. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1703. * The cross product is then orthogonal to both "left" and "right".
  1704. */
  1705. Vector3.Cross = function (left, right) {
  1706. var result = Vector3.Zero();
  1707. Vector3.CrossToRef(left, right, result);
  1708. return result;
  1709. };
  1710. /**
  1711. * Sets the passed vector "result" with the cross product of "left" and "right".
  1712. * The cross product is then orthogonal to both "left" and "right".
  1713. */
  1714. Vector3.CrossToRef = function (left, right, result) {
  1715. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1716. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1717. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1718. result.copyFrom(MathTmp.Vector3[0]);
  1719. };
  1720. /**
  1721. * Returns a new Vector3 as the normalization of the passed vector.
  1722. */
  1723. Vector3.Normalize = function (vector) {
  1724. var result = Vector3.Zero();
  1725. Vector3.NormalizeToRef(vector, result);
  1726. return result;
  1727. };
  1728. /**
  1729. * Sets the passed vector "result" with the normalization of the passed first vector.
  1730. */
  1731. Vector3.NormalizeToRef = function (vector, result) {
  1732. result.copyFrom(vector);
  1733. result.normalize();
  1734. };
  1735. Vector3.Project = function (vector, world, transform, viewport) {
  1736. var cw = viewport.width;
  1737. var ch = viewport.height;
  1738. var cx = viewport.x;
  1739. var cy = viewport.y;
  1740. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1741. 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);
  1742. var matrix = MathTmp.Matrix[0];
  1743. world.multiplyToRef(transform, matrix);
  1744. matrix.multiplyToRef(viewportMatrix, matrix);
  1745. return Vector3.TransformCoordinates(vector, matrix);
  1746. };
  1747. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1748. var matrix = MathTmp.Matrix[0];
  1749. world.multiplyToRef(transform, matrix);
  1750. matrix.invert();
  1751. source.x = source.x / viewportWidth * 2 - 1;
  1752. source.y = -(source.y / viewportHeight * 2 - 1);
  1753. var vector = Vector3.TransformCoordinates(source, matrix);
  1754. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1755. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1756. vector = vector.scale(1.0 / num);
  1757. }
  1758. return vector;
  1759. };
  1760. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1761. var matrix = MathTmp.Matrix[0];
  1762. world.multiplyToRef(view, matrix);
  1763. matrix.multiplyToRef(projection, matrix);
  1764. matrix.invert();
  1765. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1766. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1767. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1768. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1769. vector = vector.scale(1.0 / num);
  1770. }
  1771. return vector;
  1772. };
  1773. Vector3.Minimize = function (left, right) {
  1774. var min = left.clone();
  1775. min.MinimizeInPlace(right);
  1776. return min;
  1777. };
  1778. Vector3.Maximize = function (left, right) {
  1779. var max = left.clone();
  1780. max.MaximizeInPlace(right);
  1781. return max;
  1782. };
  1783. /**
  1784. * Returns the distance (float) between the vectors "value1" and "value2".
  1785. */
  1786. Vector3.Distance = function (value1, value2) {
  1787. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1788. };
  1789. /**
  1790. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1791. */
  1792. Vector3.DistanceSquared = function (value1, value2) {
  1793. var x = value1.x - value2.x;
  1794. var y = value1.y - value2.y;
  1795. var z = value1.z - value2.z;
  1796. return (x * x) + (y * y) + (z * z);
  1797. };
  1798. /**
  1799. * Returns a new Vector3 located at the center between "value1" and "value2".
  1800. */
  1801. Vector3.Center = function (value1, value2) {
  1802. var center = value1.add(value2);
  1803. center.scaleInPlace(0.5);
  1804. return center;
  1805. };
  1806. /**
  1807. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1808. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1809. * to something in order to rotate it from its local system to the given target system.
  1810. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1811. * Returns a new Vector3.
  1812. */
  1813. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1814. var rotation = Vector3.Zero();
  1815. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1816. return rotation;
  1817. };
  1818. /**
  1819. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1820. */
  1821. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1822. var quat = MathTmp.Quaternion[0];
  1823. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1824. quat.toEulerAnglesToRef(ref);
  1825. };
  1826. return Vector3;
  1827. }());
  1828. BABYLON.Vector3 = Vector3;
  1829. //Vector4 class created for EulerAngle class conversion to Quaternion
  1830. var Vector4 = /** @class */ (function () {
  1831. /**
  1832. * Creates a Vector4 object from the passed floats.
  1833. */
  1834. function Vector4(x, y, z, w) {
  1835. this.x = x;
  1836. this.y = y;
  1837. this.z = z;
  1838. this.w = w;
  1839. }
  1840. /**
  1841. * Returns the string with the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.toString = function () {
  1844. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1845. };
  1846. /**
  1847. * Returns the string "Vector4".
  1848. */
  1849. Vector4.prototype.getClassName = function () {
  1850. return "Vector4";
  1851. };
  1852. /**
  1853. * Returns the Vector4 hash code.
  1854. */
  1855. Vector4.prototype.getHashCode = function () {
  1856. var hash = this.x || 0;
  1857. hash = (hash * 397) ^ (this.y || 0);
  1858. hash = (hash * 397) ^ (this.z || 0);
  1859. hash = (hash * 397) ^ (this.w || 0);
  1860. return hash;
  1861. };
  1862. // Operators
  1863. /**
  1864. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1865. */
  1866. Vector4.prototype.asArray = function () {
  1867. var result = new Array();
  1868. this.toArray(result, 0);
  1869. return result;
  1870. };
  1871. /**
  1872. * Populates the passed array from the passed index with the Vector4 coordinates.
  1873. * Returns the Vector4.
  1874. */
  1875. Vector4.prototype.toArray = function (array, index) {
  1876. if (index === undefined) {
  1877. index = 0;
  1878. }
  1879. array[index] = this.x;
  1880. array[index + 1] = this.y;
  1881. array[index + 2] = this.z;
  1882. array[index + 3] = this.w;
  1883. return this;
  1884. };
  1885. /**
  1886. * Adds the passed vector to the current Vector4.
  1887. * Returns the updated Vector4.
  1888. */
  1889. Vector4.prototype.addInPlace = function (otherVector) {
  1890. this.x += otherVector.x;
  1891. this.y += otherVector.y;
  1892. this.z += otherVector.z;
  1893. this.w += otherVector.w;
  1894. return this;
  1895. };
  1896. /**
  1897. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1898. */
  1899. Vector4.prototype.add = function (otherVector) {
  1900. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1901. };
  1902. /**
  1903. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1904. * Returns the current Vector4.
  1905. */
  1906. Vector4.prototype.addToRef = function (otherVector, result) {
  1907. result.x = this.x + otherVector.x;
  1908. result.y = this.y + otherVector.y;
  1909. result.z = this.z + otherVector.z;
  1910. result.w = this.w + otherVector.w;
  1911. return this;
  1912. };
  1913. /**
  1914. * Subtract in place the passed vector from the current Vector4.
  1915. * Returns the updated Vector4.
  1916. */
  1917. Vector4.prototype.subtractInPlace = function (otherVector) {
  1918. this.x -= otherVector.x;
  1919. this.y -= otherVector.y;
  1920. this.z -= otherVector.z;
  1921. this.w -= otherVector.w;
  1922. return this;
  1923. };
  1924. /**
  1925. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1926. */
  1927. Vector4.prototype.subtract = function (otherVector) {
  1928. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1929. };
  1930. /**
  1931. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1932. * Returns the current Vector4.
  1933. */
  1934. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1935. result.x = this.x - otherVector.x;
  1936. result.y = this.y - otherVector.y;
  1937. result.z = this.z - otherVector.z;
  1938. result.w = this.w - otherVector.w;
  1939. return this;
  1940. };
  1941. /**
  1942. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1943. */
  1944. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1945. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1946. };
  1947. /**
  1948. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1949. * Returns the current Vector4.
  1950. */
  1951. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1952. result.x = this.x - x;
  1953. result.y = this.y - y;
  1954. result.z = this.z - z;
  1955. result.w = this.w - w;
  1956. return this;
  1957. };
  1958. /**
  1959. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1960. */
  1961. Vector4.prototype.negate = function () {
  1962. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1963. };
  1964. /**
  1965. * Multiplies the current Vector4 coordinates by scale (float).
  1966. * Returns the updated Vector4.
  1967. */
  1968. Vector4.prototype.scaleInPlace = function (scale) {
  1969. this.x *= scale;
  1970. this.y *= scale;
  1971. this.z *= scale;
  1972. this.w *= scale;
  1973. return this;
  1974. };
  1975. /**
  1976. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1977. */
  1978. Vector4.prototype.scale = function (scale) {
  1979. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1980. };
  1981. /**
  1982. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1983. * Returns the current Vector4.
  1984. */
  1985. Vector4.prototype.scaleToRef = function (scale, result) {
  1986. result.x = this.x * scale;
  1987. result.y = this.y * scale;
  1988. result.z = this.z * scale;
  1989. result.w = this.w * scale;
  1990. return this;
  1991. };
  1992. /**
  1993. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1994. */
  1995. Vector4.prototype.equals = function (otherVector) {
  1996. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1997. };
  1998. /**
  1999. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2000. */
  2001. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2002. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2003. return otherVector
  2004. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2005. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2006. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2007. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2008. };
  2009. /**
  2010. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2011. */
  2012. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2013. return this.x === x && this.y === y && this.z === z && this.w === w;
  2014. };
  2015. /**
  2016. * Multiplies in place the current Vector4 by the passed one.
  2017. * Returns the updated Vector4.
  2018. */
  2019. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2020. this.x *= otherVector.x;
  2021. this.y *= otherVector.y;
  2022. this.z *= otherVector.z;
  2023. this.w *= otherVector.w;
  2024. return this;
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2028. */
  2029. Vector4.prototype.multiply = function (otherVector) {
  2030. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2037. result.x = this.x * otherVector.x;
  2038. result.y = this.y * otherVector.y;
  2039. result.z = this.z * otherVector.z;
  2040. result.w = this.w * otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2045. */
  2046. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2047. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2048. };
  2049. /**
  2050. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2051. */
  2052. Vector4.prototype.divide = function (otherVector) {
  2053. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2054. };
  2055. /**
  2056. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2057. * Returns the current Vector4.
  2058. */
  2059. Vector4.prototype.divideToRef = function (otherVector, result) {
  2060. result.x = this.x / otherVector.x;
  2061. result.y = this.y / otherVector.y;
  2062. result.z = this.z / otherVector.z;
  2063. result.w = this.w / otherVector.w;
  2064. return this;
  2065. };
  2066. /**
  2067. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2068. */
  2069. Vector4.prototype.MinimizeInPlace = function (other) {
  2070. if (other.x < this.x)
  2071. this.x = other.x;
  2072. if (other.y < this.y)
  2073. this.y = other.y;
  2074. if (other.z < this.z)
  2075. this.z = other.z;
  2076. if (other.w < this.w)
  2077. this.w = other.w;
  2078. return this;
  2079. };
  2080. /**
  2081. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2082. */
  2083. Vector4.prototype.MaximizeInPlace = function (other) {
  2084. if (other.x > this.x)
  2085. this.x = other.x;
  2086. if (other.y > this.y)
  2087. this.y = other.y;
  2088. if (other.z > this.z)
  2089. this.z = other.z;
  2090. if (other.w > this.w)
  2091. this.w = other.w;
  2092. return this;
  2093. };
  2094. // Properties
  2095. /**
  2096. * Returns the Vector4 length (float).
  2097. */
  2098. Vector4.prototype.length = function () {
  2099. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2100. };
  2101. /**
  2102. * Returns the Vector4 squared length (float).
  2103. */
  2104. Vector4.prototype.lengthSquared = function () {
  2105. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2106. };
  2107. // Methods
  2108. /**
  2109. * Normalizes in place the Vector4.
  2110. * Returns the updated Vector4.
  2111. */
  2112. Vector4.prototype.normalize = function () {
  2113. var len = this.length();
  2114. if (len === 0)
  2115. return this;
  2116. var num = 1.0 / len;
  2117. this.x *= num;
  2118. this.y *= num;
  2119. this.z *= num;
  2120. this.w *= num;
  2121. return this;
  2122. };
  2123. /**
  2124. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2125. */
  2126. Vector4.prototype.toVector3 = function () {
  2127. return new Vector3(this.x, this.y, this.z);
  2128. };
  2129. /**
  2130. * Returns a new Vector4 copied from the current one.
  2131. */
  2132. Vector4.prototype.clone = function () {
  2133. return new Vector4(this.x, this.y, this.z, this.w);
  2134. };
  2135. /**
  2136. * Updates the current Vector4 with the passed one coordinates.
  2137. * Returns the updated Vector4.
  2138. */
  2139. Vector4.prototype.copyFrom = function (source) {
  2140. this.x = source.x;
  2141. this.y = source.y;
  2142. this.z = source.z;
  2143. this.w = source.w;
  2144. return this;
  2145. };
  2146. /**
  2147. * Updates the current Vector4 coordinates with the passed floats.
  2148. * Returns the updated Vector4.
  2149. */
  2150. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2151. this.x = x;
  2152. this.y = y;
  2153. this.z = z;
  2154. this.w = w;
  2155. return this;
  2156. };
  2157. /**
  2158. * Updates the current Vector4 coordinates with the passed floats.
  2159. * Returns the updated Vector4.
  2160. */
  2161. Vector4.prototype.set = function (x, y, z, w) {
  2162. return this.copyFromFloats(x, y, z, w);
  2163. };
  2164. // Statics
  2165. /**
  2166. * Returns a new Vector4 set from the starting index of the passed array.
  2167. */
  2168. Vector4.FromArray = function (array, offset) {
  2169. if (!offset) {
  2170. offset = 0;
  2171. }
  2172. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2173. };
  2174. /**
  2175. * Updates the passed vector "result" from the starting index of the passed array.
  2176. */
  2177. Vector4.FromArrayToRef = function (array, offset, result) {
  2178. result.x = array[offset];
  2179. result.y = array[offset + 1];
  2180. result.z = array[offset + 2];
  2181. result.w = array[offset + 3];
  2182. };
  2183. /**
  2184. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2185. */
  2186. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2187. Vector4.FromArrayToRef(array, offset, result);
  2188. };
  2189. /**
  2190. * Updates the passed vector "result" coordinates from the passed floats.
  2191. */
  2192. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2193. result.x = x;
  2194. result.y = y;
  2195. result.z = z;
  2196. result.w = w;
  2197. };
  2198. /**
  2199. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2200. */
  2201. Vector4.Zero = function () {
  2202. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2203. };
  2204. /**
  2205. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2206. */
  2207. Vector4.One = function () {
  2208. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2209. };
  2210. /**
  2211. * Returns a new normalized Vector4 from the passed one.
  2212. */
  2213. Vector4.Normalize = function (vector) {
  2214. var result = Vector4.Zero();
  2215. Vector4.NormalizeToRef(vector, result);
  2216. return result;
  2217. };
  2218. /**
  2219. * Updates the passed vector "result" from the normalization of the passed one.
  2220. */
  2221. Vector4.NormalizeToRef = function (vector, result) {
  2222. result.copyFrom(vector);
  2223. result.normalize();
  2224. };
  2225. Vector4.Minimize = function (left, right) {
  2226. var min = left.clone();
  2227. min.MinimizeInPlace(right);
  2228. return min;
  2229. };
  2230. Vector4.Maximize = function (left, right) {
  2231. var max = left.clone();
  2232. max.MaximizeInPlace(right);
  2233. return max;
  2234. };
  2235. /**
  2236. * Returns the distance (float) between the vectors "value1" and "value2".
  2237. */
  2238. Vector4.Distance = function (value1, value2) {
  2239. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2240. };
  2241. /**
  2242. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2243. */
  2244. Vector4.DistanceSquared = function (value1, value2) {
  2245. var x = value1.x - value2.x;
  2246. var y = value1.y - value2.y;
  2247. var z = value1.z - value2.z;
  2248. var w = value1.w - value2.w;
  2249. return (x * x) + (y * y) + (z * z) + (w * w);
  2250. };
  2251. /**
  2252. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2253. */
  2254. Vector4.Center = function (value1, value2) {
  2255. var center = value1.add(value2);
  2256. center.scaleInPlace(0.5);
  2257. return center;
  2258. };
  2259. /**
  2260. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2261. * This methods computes transformed normalized direction vectors only.
  2262. */
  2263. Vector4.TransformNormal = function (vector, transformation) {
  2264. var result = Vector4.Zero();
  2265. Vector4.TransformNormalToRef(vector, transformation, result);
  2266. return result;
  2267. };
  2268. /**
  2269. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2270. * This methods computes transformed normalized direction vectors only.
  2271. */
  2272. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2273. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2274. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2275. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2276. result.x = x;
  2277. result.y = y;
  2278. result.z = z;
  2279. result.w = vector.w;
  2280. };
  2281. /**
  2282. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2283. * This methods computes transformed normalized direction vectors only.
  2284. */
  2285. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2286. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2287. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2288. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2289. result.w = w;
  2290. };
  2291. return Vector4;
  2292. }());
  2293. BABYLON.Vector4 = Vector4;
  2294. var Size = /** @class */ (function () {
  2295. /**
  2296. * Creates a Size object from the passed width and height (floats).
  2297. */
  2298. function Size(width, height) {
  2299. this.width = width;
  2300. this.height = height;
  2301. }
  2302. // Returns a string with the Size width and height.
  2303. Size.prototype.toString = function () {
  2304. return "{W: " + this.width + ", H: " + this.height + "}";
  2305. };
  2306. /**
  2307. * Returns the string "Size"
  2308. */
  2309. Size.prototype.getClassName = function () {
  2310. return "Size";
  2311. };
  2312. /**
  2313. * Returns the Size hash code.
  2314. */
  2315. Size.prototype.getHashCode = function () {
  2316. var hash = this.width || 0;
  2317. hash = (hash * 397) ^ (this.height || 0);
  2318. return hash;
  2319. };
  2320. /**
  2321. * Updates the current size from the passed one.
  2322. * Returns the updated Size.
  2323. */
  2324. Size.prototype.copyFrom = function (src) {
  2325. this.width = src.width;
  2326. this.height = src.height;
  2327. };
  2328. /**
  2329. * Updates in place the current Size from the passed floats.
  2330. * Returns the updated Size.
  2331. */
  2332. Size.prototype.copyFromFloats = function (width, height) {
  2333. this.width = width;
  2334. this.height = height;
  2335. return this;
  2336. };
  2337. /**
  2338. * Updates in place the current Size from the passed floats.
  2339. * Returns the updated Size.
  2340. */
  2341. Size.prototype.set = function (width, height) {
  2342. return this.copyFromFloats(width, height);
  2343. };
  2344. /**
  2345. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2346. */
  2347. Size.prototype.multiplyByFloats = function (w, h) {
  2348. return new Size(this.width * w, this.height * h);
  2349. };
  2350. /**
  2351. * Returns a new Size copied from the passed one.
  2352. */
  2353. Size.prototype.clone = function () {
  2354. return new Size(this.width, this.height);
  2355. };
  2356. /**
  2357. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2358. */
  2359. Size.prototype.equals = function (other) {
  2360. if (!other) {
  2361. return false;
  2362. }
  2363. return (this.width === other.width) && (this.height === other.height);
  2364. };
  2365. Object.defineProperty(Size.prototype, "surface", {
  2366. /**
  2367. * Returns the surface of the Size : width * height (float).
  2368. */
  2369. get: function () {
  2370. return this.width * this.height;
  2371. },
  2372. enumerable: true,
  2373. configurable: true
  2374. });
  2375. /**
  2376. * Returns a new Size set to (0.0, 0.0)
  2377. */
  2378. Size.Zero = function () {
  2379. return new Size(0.0, 0.0);
  2380. };
  2381. /**
  2382. * Returns a new Size set as the addition result of the current Size and the passed one.
  2383. */
  2384. Size.prototype.add = function (otherSize) {
  2385. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2386. return r;
  2387. };
  2388. /**
  2389. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2390. */
  2391. Size.prototype.subtract = function (otherSize) {
  2392. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2393. return r;
  2394. };
  2395. /**
  2396. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2397. */
  2398. Size.Lerp = function (start, end, amount) {
  2399. var w = start.width + ((end.width - start.width) * amount);
  2400. var h = start.height + ((end.height - start.height) * amount);
  2401. return new Size(w, h);
  2402. };
  2403. return Size;
  2404. }());
  2405. BABYLON.Size = Size;
  2406. var Quaternion = /** @class */ (function () {
  2407. /**
  2408. * Creates a new Quaternion from the passed floats.
  2409. */
  2410. function Quaternion(x, y, z, w) {
  2411. if (x === void 0) { x = 0.0; }
  2412. if (y === void 0) { y = 0.0; }
  2413. if (z === void 0) { z = 0.0; }
  2414. if (w === void 0) { w = 1.0; }
  2415. this.x = x;
  2416. this.y = y;
  2417. this.z = z;
  2418. this.w = w;
  2419. }
  2420. /**
  2421. * Returns a string with the Quaternion coordinates.
  2422. */
  2423. Quaternion.prototype.toString = function () {
  2424. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2425. };
  2426. /**
  2427. * Returns the string "Quaternion".
  2428. */
  2429. Quaternion.prototype.getClassName = function () {
  2430. return "Quaternion";
  2431. };
  2432. /**
  2433. * Returns the Quaternion hash code.
  2434. */
  2435. Quaternion.prototype.getHashCode = function () {
  2436. var hash = this.x || 0;
  2437. hash = (hash * 397) ^ (this.y || 0);
  2438. hash = (hash * 397) ^ (this.z || 0);
  2439. hash = (hash * 397) ^ (this.w || 0);
  2440. return hash;
  2441. };
  2442. /**
  2443. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2444. */
  2445. Quaternion.prototype.asArray = function () {
  2446. return [this.x, this.y, this.z, this.w];
  2447. };
  2448. /**
  2449. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2450. */
  2451. Quaternion.prototype.equals = function (otherQuaternion) {
  2452. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2453. };
  2454. /**
  2455. * Returns a new Quaternion copied from the current one.
  2456. */
  2457. Quaternion.prototype.clone = function () {
  2458. return new Quaternion(this.x, this.y, this.z, this.w);
  2459. };
  2460. /**
  2461. * Updates the current Quaternion from the passed one coordinates.
  2462. * Returns the updated Quaterion.
  2463. */
  2464. Quaternion.prototype.copyFrom = function (other) {
  2465. this.x = other.x;
  2466. this.y = other.y;
  2467. this.z = other.z;
  2468. this.w = other.w;
  2469. return this;
  2470. };
  2471. /**
  2472. * Updates the current Quaternion from the passed float coordinates.
  2473. * Returns the updated Quaterion.
  2474. */
  2475. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2476. this.x = x;
  2477. this.y = y;
  2478. this.z = z;
  2479. this.w = w;
  2480. return this;
  2481. };
  2482. /**
  2483. * Updates the current Quaternion from the passed float coordinates.
  2484. * Returns the updated Quaterion.
  2485. */
  2486. Quaternion.prototype.set = function (x, y, z, w) {
  2487. return this.copyFromFloats(x, y, z, w);
  2488. };
  2489. /**
  2490. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2491. */
  2492. Quaternion.prototype.add = function (other) {
  2493. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2494. };
  2495. /**
  2496. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2497. */
  2498. Quaternion.prototype.subtract = function (other) {
  2499. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2500. };
  2501. /**
  2502. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2503. */
  2504. Quaternion.prototype.scale = function (value) {
  2505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2506. };
  2507. /**
  2508. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2509. */
  2510. Quaternion.prototype.multiply = function (q1) {
  2511. var result = new Quaternion(0, 0, 0, 1.0);
  2512. this.multiplyToRef(q1, result);
  2513. return result;
  2514. };
  2515. /**
  2516. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2517. * Returns the current Quaternion.
  2518. */
  2519. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2520. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2521. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2522. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2523. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2524. result.copyFromFloats(x, y, z, w);
  2525. return this;
  2526. };
  2527. /**
  2528. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2529. * Returns the updated Quaternion.
  2530. */
  2531. Quaternion.prototype.multiplyInPlace = function (q1) {
  2532. this.multiplyToRef(q1, this);
  2533. return this;
  2534. };
  2535. /**
  2536. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2537. * Returns the current Quaternion.
  2538. */
  2539. Quaternion.prototype.conjugateToRef = function (ref) {
  2540. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2541. return this;
  2542. };
  2543. /**
  2544. * Conjugates in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.conjugateInPlace = function () {
  2548. this.x *= -1;
  2549. this.y *= -1;
  2550. this.z *= -1;
  2551. return this;
  2552. };
  2553. /**
  2554. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2555. */
  2556. Quaternion.prototype.conjugate = function () {
  2557. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2558. return result;
  2559. };
  2560. /**
  2561. * Returns the Quaternion length (float).
  2562. */
  2563. Quaternion.prototype.length = function () {
  2564. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2565. };
  2566. /**
  2567. * Normalize in place the current Quaternion.
  2568. * Returns the updated Quaternion.
  2569. */
  2570. Quaternion.prototype.normalize = function () {
  2571. var length = 1.0 / this.length();
  2572. this.x *= length;
  2573. this.y *= length;
  2574. this.z *= length;
  2575. this.w *= length;
  2576. return this;
  2577. };
  2578. /**
  2579. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2580. */
  2581. Quaternion.prototype.toEulerAngles = function (order) {
  2582. if (order === void 0) { order = "YZX"; }
  2583. var result = Vector3.Zero();
  2584. this.toEulerAnglesToRef(result, order);
  2585. return result;
  2586. };
  2587. /**
  2588. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2589. * Returns the current Quaternion.
  2590. */
  2591. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2592. if (order === void 0) { order = "YZX"; }
  2593. var qz = this.z;
  2594. var qx = this.x;
  2595. var qy = this.y;
  2596. var qw = this.w;
  2597. var sqw = qw * qw;
  2598. var sqz = qz * qz;
  2599. var sqx = qx * qx;
  2600. var sqy = qy * qy;
  2601. var zAxisY = qy * qz - qx * qw;
  2602. var limit = .4999999;
  2603. if (zAxisY < -limit) {
  2604. result.y = 2 * Math.atan2(qy, qw);
  2605. result.x = Math.PI / 2;
  2606. result.z = 0;
  2607. }
  2608. else if (zAxisY > limit) {
  2609. result.y = 2 * Math.atan2(qy, qw);
  2610. result.x = -Math.PI / 2;
  2611. result.z = 0;
  2612. }
  2613. else {
  2614. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2615. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2616. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2617. }
  2618. return this;
  2619. };
  2620. /**
  2621. * Updates the passed rotation matrix with the current Quaternion values.
  2622. * Returns the current Quaternion.
  2623. */
  2624. Quaternion.prototype.toRotationMatrix = function (result) {
  2625. var xx = this.x * this.x;
  2626. var yy = this.y * this.y;
  2627. var zz = this.z * this.z;
  2628. var xy = this.x * this.y;
  2629. var zw = this.z * this.w;
  2630. var zx = this.z * this.x;
  2631. var yw = this.y * this.w;
  2632. var yz = this.y * this.z;
  2633. var xw = this.x * this.w;
  2634. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2635. result.m[1] = 2.0 * (xy + zw);
  2636. result.m[2] = 2.0 * (zx - yw);
  2637. result.m[3] = 0;
  2638. result.m[4] = 2.0 * (xy - zw);
  2639. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2640. result.m[6] = 2.0 * (yz + xw);
  2641. result.m[7] = 0;
  2642. result.m[8] = 2.0 * (zx + yw);
  2643. result.m[9] = 2.0 * (yz - xw);
  2644. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2645. result.m[11] = 0;
  2646. result.m[12] = 0;
  2647. result.m[13] = 0;
  2648. result.m[14] = 0;
  2649. result.m[15] = 1.0;
  2650. result._markAsUpdated();
  2651. return this;
  2652. };
  2653. /**
  2654. * Updates the current Quaternion from the passed rotation matrix values.
  2655. * Returns the updated Quaternion.
  2656. */
  2657. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2658. Quaternion.FromRotationMatrixToRef(matrix, this);
  2659. return this;
  2660. };
  2661. // Statics
  2662. /**
  2663. * Returns a new Quaternion set from the passed rotation matrix values.
  2664. */
  2665. Quaternion.FromRotationMatrix = function (matrix) {
  2666. var result = new Quaternion();
  2667. Quaternion.FromRotationMatrixToRef(matrix, result);
  2668. return result;
  2669. };
  2670. /**
  2671. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2672. */
  2673. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2674. var data = matrix.m;
  2675. var m11 = data[0], m12 = data[4], m13 = data[8];
  2676. var m21 = data[1], m22 = data[5], m23 = data[9];
  2677. var m31 = data[2], m32 = data[6], m33 = data[10];
  2678. var trace = m11 + m22 + m33;
  2679. var s;
  2680. if (trace > 0) {
  2681. s = 0.5 / Math.sqrt(trace + 1.0);
  2682. result.w = 0.25 / s;
  2683. result.x = (m32 - m23) * s;
  2684. result.y = (m13 - m31) * s;
  2685. result.z = (m21 - m12) * s;
  2686. }
  2687. else if (m11 > m22 && m11 > m33) {
  2688. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2689. result.w = (m32 - m23) / s;
  2690. result.x = 0.25 * s;
  2691. result.y = (m12 + m21) / s;
  2692. result.z = (m13 + m31) / s;
  2693. }
  2694. else if (m22 > m33) {
  2695. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2696. result.w = (m13 - m31) / s;
  2697. result.x = (m12 + m21) / s;
  2698. result.y = 0.25 * s;
  2699. result.z = (m23 + m32) / s;
  2700. }
  2701. else {
  2702. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2703. result.w = (m21 - m12) / s;
  2704. result.x = (m13 + m31) / s;
  2705. result.y = (m23 + m32) / s;
  2706. result.z = 0.25 * s;
  2707. }
  2708. };
  2709. /**
  2710. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2711. */
  2712. Quaternion.Zero = function () {
  2713. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2714. };
  2715. /**
  2716. * Returns a new Quaternion as the inverted current Quaternion.
  2717. */
  2718. Quaternion.Inverse = function (q) {
  2719. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2720. };
  2721. /**
  2722. * Returns the identity Quaternion.
  2723. */
  2724. Quaternion.Identity = function () {
  2725. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2726. };
  2727. Quaternion.IsIdentity = function (quaternion) {
  2728. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2729. };
  2730. /**
  2731. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2732. */
  2733. Quaternion.RotationAxis = function (axis, angle) {
  2734. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2735. };
  2736. /**
  2737. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2738. */
  2739. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2740. var sin = Math.sin(angle / 2);
  2741. axis.normalize();
  2742. result.w = Math.cos(angle / 2);
  2743. result.x = axis.x * sin;
  2744. result.y = axis.y * sin;
  2745. result.z = axis.z * sin;
  2746. return result;
  2747. };
  2748. /**
  2749. * Retuns a new Quaternion set from the starting index of the passed array.
  2750. */
  2751. Quaternion.FromArray = function (array, offset) {
  2752. if (!offset) {
  2753. offset = 0;
  2754. }
  2755. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2756. };
  2757. /**
  2758. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2759. */
  2760. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2761. var q = new Quaternion();
  2762. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2763. return q;
  2764. };
  2765. /**
  2766. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2767. */
  2768. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2769. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2770. var halfRoll = roll * 0.5;
  2771. var halfPitch = pitch * 0.5;
  2772. var halfYaw = yaw * 0.5;
  2773. var sinRoll = Math.sin(halfRoll);
  2774. var cosRoll = Math.cos(halfRoll);
  2775. var sinPitch = Math.sin(halfPitch);
  2776. var cosPitch = Math.cos(halfPitch);
  2777. var sinYaw = Math.sin(halfYaw);
  2778. var cosYaw = Math.cos(halfYaw);
  2779. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2780. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2781. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2782. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2783. };
  2784. /**
  2785. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2786. */
  2787. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2788. var result = new Quaternion();
  2789. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2790. return result;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2794. */
  2795. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2796. // Produces a quaternion from Euler angles in the z-x-z orientation
  2797. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2798. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2799. var halfBeta = beta * 0.5;
  2800. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2801. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2802. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2803. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2804. };
  2805. /**
  2806. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2807. * cf to Vector3.RotationFromAxis() documentation.
  2808. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2809. */
  2810. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2811. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2812. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2813. return quat;
  2814. };
  2815. /**
  2816. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2817. * cf to Vector3.RotationFromAxis() documentation.
  2818. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2819. */
  2820. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2821. var rotMat = MathTmp.Matrix[0];
  2822. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2823. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2824. };
  2825. Quaternion.Slerp = function (left, right, amount) {
  2826. var result = Quaternion.Identity();
  2827. Quaternion.SlerpToRef(left, right, amount, result);
  2828. return result;
  2829. };
  2830. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2831. var num2;
  2832. var num3;
  2833. var num = amount;
  2834. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2835. var flag = false;
  2836. if (num4 < 0) {
  2837. flag = true;
  2838. num4 = -num4;
  2839. }
  2840. if (num4 > 0.999999) {
  2841. num3 = 1 - num;
  2842. num2 = flag ? -num : num;
  2843. }
  2844. else {
  2845. var num5 = Math.acos(num4);
  2846. var num6 = (1.0 / Math.sin(num5));
  2847. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2848. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2849. }
  2850. result.x = (num3 * left.x) + (num2 * right.x);
  2851. result.y = (num3 * left.y) + (num2 * right.y);
  2852. result.z = (num3 * left.z) + (num2 * right.z);
  2853. result.w = (num3 * left.w) + (num2 * right.w);
  2854. };
  2855. /**
  2856. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2857. */
  2858. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2859. var squared = amount * amount;
  2860. var cubed = amount * squared;
  2861. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2862. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2863. var part3 = (cubed - (2.0 * squared)) + amount;
  2864. var part4 = cubed - squared;
  2865. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2866. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2867. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2868. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2869. return new Quaternion(x, y, z, w);
  2870. };
  2871. return Quaternion;
  2872. }());
  2873. BABYLON.Quaternion = Quaternion;
  2874. var Matrix = /** @class */ (function () {
  2875. function Matrix() {
  2876. this._isIdentity = false;
  2877. this._isIdentityDirty = true;
  2878. this.m = new Float32Array(16);
  2879. this._markAsUpdated();
  2880. }
  2881. Matrix.prototype._markAsUpdated = function () {
  2882. this.updateFlag = Matrix._updateFlagSeed++;
  2883. this._isIdentityDirty = true;
  2884. };
  2885. // Properties
  2886. /**
  2887. * Boolean : True is the matrix is the identity matrix
  2888. */
  2889. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2890. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2891. if (this._isIdentityDirty) {
  2892. this._isIdentityDirty = false;
  2893. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2894. this._isIdentity = false;
  2895. }
  2896. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2897. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2898. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2899. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2900. this._isIdentity = false;
  2901. }
  2902. else {
  2903. this._isIdentity = true;
  2904. }
  2905. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2906. this._isIdentity = false;
  2907. }
  2908. }
  2909. return this._isIdentity;
  2910. };
  2911. /**
  2912. * Returns the matrix determinant (float).
  2913. */
  2914. Matrix.prototype.determinant = function () {
  2915. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2916. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2917. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2918. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2919. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2920. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2921. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2922. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2923. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2924. };
  2925. // Methods
  2926. /**
  2927. * Returns the matrix underlying array.
  2928. */
  2929. Matrix.prototype.toArray = function () {
  2930. return this.m;
  2931. };
  2932. /**
  2933. * Returns the matrix underlying array.
  2934. */
  2935. Matrix.prototype.asArray = function () {
  2936. return this.toArray();
  2937. };
  2938. /**
  2939. * Inverts in place the Matrix.
  2940. * Returns the Matrix inverted.
  2941. */
  2942. Matrix.prototype.invert = function () {
  2943. this.invertToRef(this);
  2944. return this;
  2945. };
  2946. /**
  2947. * Sets all the matrix elements to zero.
  2948. * Returns the Matrix.
  2949. */
  2950. Matrix.prototype.reset = function () {
  2951. for (var index = 0; index < 16; index++) {
  2952. this.m[index] = 0.0;
  2953. }
  2954. this._markAsUpdated();
  2955. return this;
  2956. };
  2957. /**
  2958. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2959. */
  2960. Matrix.prototype.add = function (other) {
  2961. var result = new Matrix();
  2962. this.addToRef(other, result);
  2963. return result;
  2964. };
  2965. /**
  2966. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2967. * Returns the Matrix.
  2968. */
  2969. Matrix.prototype.addToRef = function (other, result) {
  2970. for (var index = 0; index < 16; index++) {
  2971. result.m[index] = this.m[index] + other.m[index];
  2972. }
  2973. result._markAsUpdated();
  2974. return this;
  2975. };
  2976. /**
  2977. * Adds in place the passed matrix to the current Matrix.
  2978. * Returns the updated Matrix.
  2979. */
  2980. Matrix.prototype.addToSelf = function (other) {
  2981. for (var index = 0; index < 16; index++) {
  2982. this.m[index] += other.m[index];
  2983. }
  2984. this._markAsUpdated();
  2985. return this;
  2986. };
  2987. /**
  2988. * Sets the passed matrix with the current inverted Matrix.
  2989. * Returns the unmodified current Matrix.
  2990. */
  2991. Matrix.prototype.invertToRef = function (other) {
  2992. var l1 = this.m[0];
  2993. var l2 = this.m[1];
  2994. var l3 = this.m[2];
  2995. var l4 = this.m[3];
  2996. var l5 = this.m[4];
  2997. var l6 = this.m[5];
  2998. var l7 = this.m[6];
  2999. var l8 = this.m[7];
  3000. var l9 = this.m[8];
  3001. var l10 = this.m[9];
  3002. var l11 = this.m[10];
  3003. var l12 = this.m[11];
  3004. var l13 = this.m[12];
  3005. var l14 = this.m[13];
  3006. var l15 = this.m[14];
  3007. var l16 = this.m[15];
  3008. var l17 = (l11 * l16) - (l12 * l15);
  3009. var l18 = (l10 * l16) - (l12 * l14);
  3010. var l19 = (l10 * l15) - (l11 * l14);
  3011. var l20 = (l9 * l16) - (l12 * l13);
  3012. var l21 = (l9 * l15) - (l11 * l13);
  3013. var l22 = (l9 * l14) - (l10 * l13);
  3014. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3015. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3016. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3017. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3018. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3019. var l28 = (l7 * l16) - (l8 * l15);
  3020. var l29 = (l6 * l16) - (l8 * l14);
  3021. var l30 = (l6 * l15) - (l7 * l14);
  3022. var l31 = (l5 * l16) - (l8 * l13);
  3023. var l32 = (l5 * l15) - (l7 * l13);
  3024. var l33 = (l5 * l14) - (l6 * l13);
  3025. var l34 = (l7 * l12) - (l8 * l11);
  3026. var l35 = (l6 * l12) - (l8 * l10);
  3027. var l36 = (l6 * l11) - (l7 * l10);
  3028. var l37 = (l5 * l12) - (l8 * l9);
  3029. var l38 = (l5 * l11) - (l7 * l9);
  3030. var l39 = (l5 * l10) - (l6 * l9);
  3031. other.m[0] = l23 * l27;
  3032. other.m[4] = l24 * l27;
  3033. other.m[8] = l25 * l27;
  3034. other.m[12] = l26 * l27;
  3035. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3036. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3037. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3038. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3039. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3040. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3041. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3042. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3043. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3044. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3045. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3046. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3047. other._markAsUpdated();
  3048. return this;
  3049. };
  3050. /**
  3051. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3052. * Returns the updated Matrix.
  3053. */
  3054. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3055. this.m[12] = x;
  3056. this.m[13] = y;
  3057. this.m[14] = z;
  3058. this._markAsUpdated();
  3059. return this;
  3060. };
  3061. /**
  3062. * Inserts the translation vector in the current Matrix.
  3063. * Returns the updated Matrix.
  3064. */
  3065. Matrix.prototype.setTranslation = function (vector3) {
  3066. this.m[12] = vector3.x;
  3067. this.m[13] = vector3.y;
  3068. this.m[14] = vector3.z;
  3069. this._markAsUpdated();
  3070. return this;
  3071. };
  3072. /**
  3073. * Returns a new Vector3 as the extracted translation from the Matrix.
  3074. */
  3075. Matrix.prototype.getTranslation = function () {
  3076. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3077. };
  3078. /**
  3079. * Fill a Vector3 with the extracted translation from the Matrix.
  3080. */
  3081. Matrix.prototype.getTranslationToRef = function (result) {
  3082. result.x = this.m[12];
  3083. result.y = this.m[13];
  3084. result.z = this.m[14];
  3085. return this;
  3086. };
  3087. /**
  3088. * Remove rotation and scaling part from the Matrix.
  3089. * Returns the updated Matrix.
  3090. */
  3091. Matrix.prototype.removeRotationAndScaling = function () {
  3092. this.setRowFromFloats(0, 1, 0, 0, 0);
  3093. this.setRowFromFloats(1, 0, 1, 0, 0);
  3094. this.setRowFromFloats(2, 0, 0, 1, 0);
  3095. return this;
  3096. };
  3097. /**
  3098. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3099. */
  3100. Matrix.prototype.multiply = function (other) {
  3101. var result = new Matrix();
  3102. this.multiplyToRef(other, result);
  3103. return result;
  3104. };
  3105. /**
  3106. * Updates the current Matrix from the passed one values.
  3107. * Returns the updated Matrix.
  3108. */
  3109. Matrix.prototype.copyFrom = function (other) {
  3110. for (var index = 0; index < 16; index++) {
  3111. this.m[index] = other.m[index];
  3112. }
  3113. this._markAsUpdated();
  3114. return this;
  3115. };
  3116. /**
  3117. * Populates the passed array from the starting index with the Matrix values.
  3118. * Returns the Matrix.
  3119. */
  3120. Matrix.prototype.copyToArray = function (array, offset) {
  3121. if (offset === void 0) { offset = 0; }
  3122. for (var index = 0; index < 16; index++) {
  3123. array[offset + index] = this.m[index];
  3124. }
  3125. return this;
  3126. };
  3127. /**
  3128. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3129. */
  3130. Matrix.prototype.multiplyToRef = function (other, result) {
  3131. this.multiplyToArray(other, result.m, 0);
  3132. result._markAsUpdated();
  3133. return this;
  3134. };
  3135. /**
  3136. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3137. */
  3138. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3139. var tm0 = this.m[0];
  3140. var tm1 = this.m[1];
  3141. var tm2 = this.m[2];
  3142. var tm3 = this.m[3];
  3143. var tm4 = this.m[4];
  3144. var tm5 = this.m[5];
  3145. var tm6 = this.m[6];
  3146. var tm7 = this.m[7];
  3147. var tm8 = this.m[8];
  3148. var tm9 = this.m[9];
  3149. var tm10 = this.m[10];
  3150. var tm11 = this.m[11];
  3151. var tm12 = this.m[12];
  3152. var tm13 = this.m[13];
  3153. var tm14 = this.m[14];
  3154. var tm15 = this.m[15];
  3155. var om0 = other.m[0];
  3156. var om1 = other.m[1];
  3157. var om2 = other.m[2];
  3158. var om3 = other.m[3];
  3159. var om4 = other.m[4];
  3160. var om5 = other.m[5];
  3161. var om6 = other.m[6];
  3162. var om7 = other.m[7];
  3163. var om8 = other.m[8];
  3164. var om9 = other.m[9];
  3165. var om10 = other.m[10];
  3166. var om11 = other.m[11];
  3167. var om12 = other.m[12];
  3168. var om13 = other.m[13];
  3169. var om14 = other.m[14];
  3170. var om15 = other.m[15];
  3171. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3172. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3173. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3174. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3175. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3176. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3177. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3178. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3179. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3180. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3181. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3182. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3183. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3184. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3185. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3186. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3187. return this;
  3188. };
  3189. /**
  3190. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3191. */
  3192. Matrix.prototype.equals = function (value) {
  3193. return value &&
  3194. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3195. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3196. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3197. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3198. };
  3199. /**
  3200. * Returns a new Matrix from the current Matrix.
  3201. */
  3202. Matrix.prototype.clone = function () {
  3203. 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]);
  3204. };
  3205. /**
  3206. * Returns the string "Matrix"
  3207. */
  3208. Matrix.prototype.getClassName = function () {
  3209. return "Matrix";
  3210. };
  3211. /**
  3212. * Returns the Matrix hash code.
  3213. */
  3214. Matrix.prototype.getHashCode = function () {
  3215. var hash = this.m[0] || 0;
  3216. for (var i = 1; i < 16; i++) {
  3217. hash = (hash * 397) ^ (this.m[i] || 0);
  3218. }
  3219. return hash;
  3220. };
  3221. /**
  3222. * Decomposes the current Matrix into :
  3223. * - a scale vector3 passed as a reference to update,
  3224. * - a rotation quaternion passed as a reference to update,
  3225. * - a translation vector3 passed as a reference to update.
  3226. * Returns the boolean `true`.
  3227. */
  3228. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3229. translation.x = this.m[12];
  3230. translation.y = this.m[13];
  3231. translation.z = this.m[14];
  3232. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3233. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3234. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3235. if (this.determinant() <= 0) {
  3236. scale.y *= -1;
  3237. }
  3238. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3239. rotation.x = 0;
  3240. rotation.y = 0;
  3241. rotation.z = 0;
  3242. rotation.w = 1;
  3243. return false;
  3244. }
  3245. 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]);
  3246. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3247. return true;
  3248. };
  3249. /**
  3250. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3251. */
  3252. Matrix.prototype.getRotationMatrix = function () {
  3253. var result = Matrix.Identity();
  3254. this.getRotationMatrixToRef(result);
  3255. return result;
  3256. };
  3257. /**
  3258. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3259. * Returns the current Matrix.
  3260. */
  3261. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3262. var m = this.m;
  3263. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3264. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3265. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3266. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3267. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3268. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3269. 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);
  3270. return this;
  3271. };
  3272. // Statics
  3273. /**
  3274. * Returns a new Matrix set from the starting index of the passed array.
  3275. */
  3276. Matrix.FromArray = function (array, offset) {
  3277. var result = new Matrix();
  3278. if (!offset) {
  3279. offset = 0;
  3280. }
  3281. Matrix.FromArrayToRef(array, offset, result);
  3282. return result;
  3283. };
  3284. /**
  3285. * Sets the passed "result" matrix from the starting index of the passed array.
  3286. */
  3287. Matrix.FromArrayToRef = function (array, offset, result) {
  3288. for (var index = 0; index < 16; index++) {
  3289. result.m[index] = array[index + offset];
  3290. }
  3291. result._markAsUpdated();
  3292. };
  3293. /**
  3294. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3295. */
  3296. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3297. for (var index = 0; index < 16; index++) {
  3298. result.m[index] = array[index + offset] * scale;
  3299. }
  3300. result._markAsUpdated();
  3301. };
  3302. /**
  3303. * Sets the passed matrix "result" with the 16 passed floats.
  3304. */
  3305. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3306. result.m[0] = initialM11;
  3307. result.m[1] = initialM12;
  3308. result.m[2] = initialM13;
  3309. result.m[3] = initialM14;
  3310. result.m[4] = initialM21;
  3311. result.m[5] = initialM22;
  3312. result.m[6] = initialM23;
  3313. result.m[7] = initialM24;
  3314. result.m[8] = initialM31;
  3315. result.m[9] = initialM32;
  3316. result.m[10] = initialM33;
  3317. result.m[11] = initialM34;
  3318. result.m[12] = initialM41;
  3319. result.m[13] = initialM42;
  3320. result.m[14] = initialM43;
  3321. result.m[15] = initialM44;
  3322. result._markAsUpdated();
  3323. };
  3324. /**
  3325. * Returns the index-th row of the current matrix as a new Vector4.
  3326. */
  3327. Matrix.prototype.getRow = function (index) {
  3328. if (index < 0 || index > 3) {
  3329. return null;
  3330. }
  3331. var i = index * 4;
  3332. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3333. };
  3334. /**
  3335. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3336. * Returns the updated Matrix.
  3337. */
  3338. Matrix.prototype.setRow = function (index, row) {
  3339. if (index < 0 || index > 3) {
  3340. return this;
  3341. }
  3342. var i = index * 4;
  3343. this.m[i + 0] = row.x;
  3344. this.m[i + 1] = row.y;
  3345. this.m[i + 2] = row.z;
  3346. this.m[i + 3] = row.w;
  3347. this._markAsUpdated();
  3348. return this;
  3349. };
  3350. /**
  3351. * Compute the transpose of the matrix.
  3352. * Returns a new Matrix.
  3353. */
  3354. Matrix.prototype.transpose = function () {
  3355. return Matrix.Transpose(this);
  3356. };
  3357. /**
  3358. * Compute the transpose of the matrix.
  3359. * Returns the current matrix.
  3360. */
  3361. Matrix.prototype.transposeToRef = function (result) {
  3362. Matrix.TransposeToRef(this, result);
  3363. return this;
  3364. };
  3365. /**
  3366. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3367. * Returns the updated Matrix.
  3368. */
  3369. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3370. if (index < 0 || index > 3) {
  3371. return this;
  3372. }
  3373. var i = index * 4;
  3374. this.m[i + 0] = x;
  3375. this.m[i + 1] = y;
  3376. this.m[i + 2] = z;
  3377. this.m[i + 3] = w;
  3378. this._markAsUpdated();
  3379. return this;
  3380. };
  3381. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3382. /**
  3383. * Static identity matrix to be used as readonly matrix
  3384. * Must not be updated.
  3385. */
  3386. get: function () {
  3387. return Matrix._identityReadOnly;
  3388. },
  3389. enumerable: true,
  3390. configurable: true
  3391. });
  3392. /**
  3393. * Returns a new Matrix set from the 16 passed floats.
  3394. */
  3395. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3396. var result = new Matrix();
  3397. result.m[0] = initialM11;
  3398. result.m[1] = initialM12;
  3399. result.m[2] = initialM13;
  3400. result.m[3] = initialM14;
  3401. result.m[4] = initialM21;
  3402. result.m[5] = initialM22;
  3403. result.m[6] = initialM23;
  3404. result.m[7] = initialM24;
  3405. result.m[8] = initialM31;
  3406. result.m[9] = initialM32;
  3407. result.m[10] = initialM33;
  3408. result.m[11] = initialM34;
  3409. result.m[12] = initialM41;
  3410. result.m[13] = initialM42;
  3411. result.m[14] = initialM43;
  3412. result.m[15] = initialM44;
  3413. return result;
  3414. };
  3415. /**
  3416. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3417. */
  3418. Matrix.Compose = function (scale, rotation, translation) {
  3419. var result = Matrix.Identity();
  3420. Matrix.ComposeToRef(scale, rotation, translation, result);
  3421. return result;
  3422. };
  3423. /**
  3424. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3425. */
  3426. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3427. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3428. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3429. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3430. result.setTranslation(translation);
  3431. };
  3432. /**
  3433. * Returns a new indentity Matrix.
  3434. */
  3435. Matrix.Identity = function () {
  3436. 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);
  3437. };
  3438. /**
  3439. * Sets the passed "result" as an identity matrix.
  3440. */
  3441. Matrix.IdentityToRef = function (result) {
  3442. 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);
  3443. };
  3444. /**
  3445. * Returns a new zero Matrix.
  3446. */
  3447. Matrix.Zero = function () {
  3448. 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);
  3449. };
  3450. /**
  3451. * Returns a new rotation matrix for "angle" radians around the X axis.
  3452. */
  3453. Matrix.RotationX = function (angle) {
  3454. var result = new Matrix();
  3455. Matrix.RotationXToRef(angle, result);
  3456. return result;
  3457. };
  3458. /**
  3459. * Returns a new Matrix as the passed inverted one.
  3460. */
  3461. Matrix.Invert = function (source) {
  3462. var result = new Matrix();
  3463. source.invertToRef(result);
  3464. return result;
  3465. };
  3466. /**
  3467. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3468. */
  3469. Matrix.RotationXToRef = function (angle, result) {
  3470. var s = Math.sin(angle);
  3471. var c = Math.cos(angle);
  3472. result.m[0] = 1.0;
  3473. result.m[15] = 1.0;
  3474. result.m[5] = c;
  3475. result.m[10] = c;
  3476. result.m[9] = -s;
  3477. result.m[6] = s;
  3478. result.m[1] = 0.0;
  3479. result.m[2] = 0.0;
  3480. result.m[3] = 0.0;
  3481. result.m[4] = 0.0;
  3482. result.m[7] = 0.0;
  3483. result.m[8] = 0.0;
  3484. result.m[11] = 0.0;
  3485. result.m[12] = 0.0;
  3486. result.m[13] = 0.0;
  3487. result.m[14] = 0.0;
  3488. result._markAsUpdated();
  3489. };
  3490. /**
  3491. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3492. */
  3493. Matrix.RotationY = function (angle) {
  3494. var result = new Matrix();
  3495. Matrix.RotationYToRef(angle, result);
  3496. return result;
  3497. };
  3498. /**
  3499. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3500. */
  3501. Matrix.RotationYToRef = function (angle, result) {
  3502. var s = Math.sin(angle);
  3503. var c = Math.cos(angle);
  3504. result.m[5] = 1.0;
  3505. result.m[15] = 1.0;
  3506. result.m[0] = c;
  3507. result.m[2] = -s;
  3508. result.m[8] = s;
  3509. result.m[10] = c;
  3510. result.m[1] = 0.0;
  3511. result.m[3] = 0.0;
  3512. result.m[4] = 0.0;
  3513. result.m[6] = 0.0;
  3514. result.m[7] = 0.0;
  3515. result.m[9] = 0.0;
  3516. result.m[11] = 0.0;
  3517. result.m[12] = 0.0;
  3518. result.m[13] = 0.0;
  3519. result.m[14] = 0.0;
  3520. result._markAsUpdated();
  3521. };
  3522. /**
  3523. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3524. */
  3525. Matrix.RotationZ = function (angle) {
  3526. var result = new Matrix();
  3527. Matrix.RotationZToRef(angle, result);
  3528. return result;
  3529. };
  3530. /**
  3531. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3532. */
  3533. Matrix.RotationZToRef = function (angle, result) {
  3534. var s = Math.sin(angle);
  3535. var c = Math.cos(angle);
  3536. result.m[10] = 1.0;
  3537. result.m[15] = 1.0;
  3538. result.m[0] = c;
  3539. result.m[1] = s;
  3540. result.m[4] = -s;
  3541. result.m[5] = c;
  3542. result.m[2] = 0.0;
  3543. result.m[3] = 0.0;
  3544. result.m[6] = 0.0;
  3545. result.m[7] = 0.0;
  3546. result.m[8] = 0.0;
  3547. result.m[9] = 0.0;
  3548. result.m[11] = 0.0;
  3549. result.m[12] = 0.0;
  3550. result.m[13] = 0.0;
  3551. result.m[14] = 0.0;
  3552. result._markAsUpdated();
  3553. };
  3554. /**
  3555. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3556. */
  3557. Matrix.RotationAxis = function (axis, angle) {
  3558. var result = Matrix.Zero();
  3559. Matrix.RotationAxisToRef(axis, angle, result);
  3560. return result;
  3561. };
  3562. /**
  3563. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3564. */
  3565. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3566. var s = Math.sin(-angle);
  3567. var c = Math.cos(-angle);
  3568. var c1 = 1 - c;
  3569. axis.normalize();
  3570. result.m[0] = (axis.x * axis.x) * c1 + c;
  3571. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3572. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3573. result.m[3] = 0.0;
  3574. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3575. result.m[5] = (axis.y * axis.y) * c1 + c;
  3576. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3577. result.m[7] = 0.0;
  3578. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3579. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3580. result.m[10] = (axis.z * axis.z) * c1 + c;
  3581. result.m[11] = 0.0;
  3582. result.m[15] = 1.0;
  3583. result._markAsUpdated();
  3584. };
  3585. /**
  3586. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3587. */
  3588. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3589. var result = new Matrix();
  3590. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3591. return result;
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3595. */
  3596. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3597. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3598. this._tempQuaternion.toRotationMatrix(result);
  3599. };
  3600. /**
  3601. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3602. */
  3603. Matrix.Scaling = function (x, y, z) {
  3604. var result = Matrix.Zero();
  3605. Matrix.ScalingToRef(x, y, z, result);
  3606. return result;
  3607. };
  3608. /**
  3609. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3610. */
  3611. Matrix.ScalingToRef = function (x, y, z, result) {
  3612. result.m[0] = x;
  3613. result.m[1] = 0.0;
  3614. result.m[2] = 0.0;
  3615. result.m[3] = 0.0;
  3616. result.m[4] = 0.0;
  3617. result.m[5] = y;
  3618. result.m[6] = 0.0;
  3619. result.m[7] = 0.0;
  3620. result.m[8] = 0.0;
  3621. result.m[9] = 0.0;
  3622. result.m[10] = z;
  3623. result.m[11] = 0.0;
  3624. result.m[12] = 0.0;
  3625. result.m[13] = 0.0;
  3626. result.m[14] = 0.0;
  3627. result.m[15] = 1.0;
  3628. result._markAsUpdated();
  3629. };
  3630. /**
  3631. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3632. */
  3633. Matrix.Translation = function (x, y, z) {
  3634. var result = Matrix.Identity();
  3635. Matrix.TranslationToRef(x, y, z, result);
  3636. return result;
  3637. };
  3638. /**
  3639. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3640. */
  3641. Matrix.TranslationToRef = function (x, y, z, result) {
  3642. 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);
  3643. };
  3644. /**
  3645. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3646. */
  3647. Matrix.Lerp = function (startValue, endValue, gradient) {
  3648. var result = Matrix.Zero();
  3649. for (var index = 0; index < 16; index++) {
  3650. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3651. }
  3652. result._markAsUpdated();
  3653. return result;
  3654. };
  3655. /**
  3656. * Returns a new Matrix whose values are computed by :
  3657. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3658. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3659. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3660. */
  3661. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3662. var startScale = new Vector3(0, 0, 0);
  3663. var startRotation = new Quaternion();
  3664. var startTranslation = new Vector3(0, 0, 0);
  3665. startValue.decompose(startScale, startRotation, startTranslation);
  3666. var endScale = new Vector3(0, 0, 0);
  3667. var endRotation = new Quaternion();
  3668. var endTranslation = new Vector3(0, 0, 0);
  3669. endValue.decompose(endScale, endRotation, endTranslation);
  3670. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3671. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3672. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3673. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3674. };
  3675. /**
  3676. * 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".
  3677. * This methods works for a Left-Handed system.
  3678. */
  3679. Matrix.LookAtLH = function (eye, target, up) {
  3680. var result = Matrix.Zero();
  3681. Matrix.LookAtLHToRef(eye, target, up, result);
  3682. return result;
  3683. };
  3684. /**
  3685. * 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".
  3686. * This methods works for a Left-Handed system.
  3687. */
  3688. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3689. // Z axis
  3690. target.subtractToRef(eye, this._zAxis);
  3691. this._zAxis.normalize();
  3692. // X axis
  3693. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3694. if (this._xAxis.lengthSquared() === 0) {
  3695. this._xAxis.x = 1.0;
  3696. }
  3697. else {
  3698. this._xAxis.normalize();
  3699. }
  3700. // Y axis
  3701. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3702. this._yAxis.normalize();
  3703. // Eye angles
  3704. var ex = -Vector3.Dot(this._xAxis, eye);
  3705. var ey = -Vector3.Dot(this._yAxis, eye);
  3706. var ez = -Vector3.Dot(this._zAxis, eye);
  3707. 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);
  3708. };
  3709. /**
  3710. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3711. * This methods works for a Right-Handed system.
  3712. */
  3713. Matrix.LookAtRH = function (eye, target, up) {
  3714. var result = Matrix.Zero();
  3715. Matrix.LookAtRHToRef(eye, target, up, result);
  3716. return result;
  3717. };
  3718. /**
  3719. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3720. * This methods works for a Left-Handed system.
  3721. */
  3722. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3723. // Z axis
  3724. eye.subtractToRef(target, this._zAxis);
  3725. this._zAxis.normalize();
  3726. // X axis
  3727. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3728. if (this._xAxis.lengthSquared() === 0) {
  3729. this._xAxis.x = 1.0;
  3730. }
  3731. else {
  3732. this._xAxis.normalize();
  3733. }
  3734. // Y axis
  3735. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3736. this._yAxis.normalize();
  3737. // Eye angles
  3738. var ex = -Vector3.Dot(this._xAxis, eye);
  3739. var ey = -Vector3.Dot(this._yAxis, eye);
  3740. var ez = -Vector3.Dot(this._zAxis, eye);
  3741. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3742. };
  3743. /**
  3744. * Returns a new 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.
  3745. */
  3746. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3747. var matrix = Matrix.Zero();
  3748. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3749. return matrix;
  3750. };
  3751. /**
  3752. * 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.
  3753. */
  3754. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3755. var n = znear;
  3756. var f = zfar;
  3757. var a = 2.0 / width;
  3758. var b = 2.0 / height;
  3759. var c = 2.0 / (f - n);
  3760. var d = -(f + n) / (f - n);
  3761. BABYLON.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);
  3762. };
  3763. /**
  3764. * 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.
  3765. */
  3766. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3767. var matrix = Matrix.Zero();
  3768. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3769. return matrix;
  3770. };
  3771. /**
  3772. * 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.
  3773. */
  3774. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3775. var n = znear;
  3776. var f = zfar;
  3777. var a = 2.0 / (right - left);
  3778. var b = 2.0 / (top - bottom);
  3779. var c = 2.0 / (f - n);
  3780. var d = -(f + n) / (f - n);
  3781. var i0 = (left + right) / (left - right);
  3782. var i1 = (top + bottom) / (bottom - top);
  3783. BABYLON.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);
  3784. };
  3785. /**
  3786. * 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.
  3787. */
  3788. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3789. var matrix = Matrix.Zero();
  3790. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3791. return matrix;
  3792. };
  3793. /**
  3794. * 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.
  3795. */
  3796. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3797. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3798. result.m[10] *= -1.0;
  3799. };
  3800. /**
  3801. * 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.
  3802. */
  3803. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3804. var matrix = Matrix.Zero();
  3805. var n = znear;
  3806. var f = zfar;
  3807. var a = 2.0 * n / width;
  3808. var b = 2.0 * n / height;
  3809. var c = (f + n) / (f - n);
  3810. var d = -2.0 * f * n / (f - n);
  3811. BABYLON.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);
  3812. return matrix;
  3813. };
  3814. /**
  3815. * 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.
  3816. */
  3817. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3818. var matrix = Matrix.Zero();
  3819. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3820. return matrix;
  3821. };
  3822. /**
  3823. * 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.
  3824. */
  3825. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3826. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3827. var n = znear;
  3828. var f = zfar;
  3829. var t = 1.0 / (Math.tan(fov * 0.5));
  3830. var a = isVerticalFovFixed ? (t / aspect) : t;
  3831. var b = isVerticalFovFixed ? t : (t * aspect);
  3832. var c = (f + n) / (f - n);
  3833. var d = -2.0 * f * n / (f - n);
  3834. BABYLON.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);
  3835. };
  3836. /**
  3837. * 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.
  3838. */
  3839. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3840. var matrix = Matrix.Zero();
  3841. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3842. return matrix;
  3843. };
  3844. /**
  3845. * 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.
  3846. */
  3847. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3848. //alternatively this could be expressed as:
  3849. // m = PerspectiveFovLHToRef
  3850. // m[10] *= -1.0;
  3851. // m[11] *= -1.0;
  3852. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3853. var n = znear;
  3854. var f = zfar;
  3855. var t = 1.0 / (Math.tan(fov * 0.5));
  3856. var a = isVerticalFovFixed ? (t / aspect) : t;
  3857. var b = isVerticalFovFixed ? t : (t * aspect);
  3858. var c = -(f + n) / (f - n);
  3859. var d = -2 * f * n / (f - n);
  3860. BABYLON.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);
  3861. };
  3862. /**
  3863. * 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.
  3864. */
  3865. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3866. if (rightHanded === void 0) { rightHanded = false; }
  3867. var rightHandedFactor = rightHanded ? -1 : 1;
  3868. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3869. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3870. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3871. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3872. var xScale = 2.0 / (leftTan + rightTan);
  3873. var yScale = 2.0 / (upTan + downTan);
  3874. result.m[0] = xScale;
  3875. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3876. result.m[5] = yScale;
  3877. result.m[6] = result.m[7] = 0.0;
  3878. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3879. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3880. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3881. result.m[10] = -zfar / (znear - zfar);
  3882. result.m[11] = 1.0 * rightHandedFactor;
  3883. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3884. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3885. // result.m[14] = (znear * zfar) / (znear - zfar);
  3886. result._markAsUpdated();
  3887. };
  3888. /**
  3889. * Returns the final transformation matrix : world * view * projection * viewport
  3890. */
  3891. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3892. var cw = viewport.width;
  3893. var ch = viewport.height;
  3894. var cx = viewport.x;
  3895. var cy = viewport.y;
  3896. 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);
  3897. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3898. };
  3899. /**
  3900. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3901. */
  3902. Matrix.GetAsMatrix2x2 = function (matrix) {
  3903. return new Float32Array([
  3904. matrix.m[0], matrix.m[1],
  3905. matrix.m[4], matrix.m[5]
  3906. ]);
  3907. };
  3908. /**
  3909. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3910. */
  3911. Matrix.GetAsMatrix3x3 = function (matrix) {
  3912. return new Float32Array([
  3913. matrix.m[0], matrix.m[1], matrix.m[2],
  3914. matrix.m[4], matrix.m[5], matrix.m[6],
  3915. matrix.m[8], matrix.m[9], matrix.m[10]
  3916. ]);
  3917. };
  3918. /**
  3919. * Compute the transpose of the passed Matrix.
  3920. * Returns a new Matrix.
  3921. */
  3922. Matrix.Transpose = function (matrix) {
  3923. var result = new Matrix();
  3924. Matrix.TransposeToRef(matrix, result);
  3925. return result;
  3926. };
  3927. /**
  3928. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3929. */
  3930. Matrix.TransposeToRef = function (matrix, result) {
  3931. result.m[0] = matrix.m[0];
  3932. result.m[1] = matrix.m[4];
  3933. result.m[2] = matrix.m[8];
  3934. result.m[3] = matrix.m[12];
  3935. result.m[4] = matrix.m[1];
  3936. result.m[5] = matrix.m[5];
  3937. result.m[6] = matrix.m[9];
  3938. result.m[7] = matrix.m[13];
  3939. result.m[8] = matrix.m[2];
  3940. result.m[9] = matrix.m[6];
  3941. result.m[10] = matrix.m[10];
  3942. result.m[11] = matrix.m[14];
  3943. result.m[12] = matrix.m[3];
  3944. result.m[13] = matrix.m[7];
  3945. result.m[14] = matrix.m[11];
  3946. result.m[15] = matrix.m[15];
  3947. };
  3948. /**
  3949. * Returns a new Matrix as the reflection matrix across the passed plane.
  3950. */
  3951. Matrix.Reflection = function (plane) {
  3952. var matrix = new Matrix();
  3953. Matrix.ReflectionToRef(plane, matrix);
  3954. return matrix;
  3955. };
  3956. /**
  3957. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3958. */
  3959. Matrix.ReflectionToRef = function (plane, result) {
  3960. plane.normalize();
  3961. var x = plane.normal.x;
  3962. var y = plane.normal.y;
  3963. var z = plane.normal.z;
  3964. var temp = -2 * x;
  3965. var temp2 = -2 * y;
  3966. var temp3 = -2 * z;
  3967. result.m[0] = (temp * x) + 1;
  3968. result.m[1] = temp2 * x;
  3969. result.m[2] = temp3 * x;
  3970. result.m[3] = 0.0;
  3971. result.m[4] = temp * y;
  3972. result.m[5] = (temp2 * y) + 1;
  3973. result.m[6] = temp3 * y;
  3974. result.m[7] = 0.0;
  3975. result.m[8] = temp * z;
  3976. result.m[9] = temp2 * z;
  3977. result.m[10] = (temp3 * z) + 1;
  3978. result.m[11] = 0.0;
  3979. result.m[12] = temp * plane.d;
  3980. result.m[13] = temp2 * plane.d;
  3981. result.m[14] = temp3 * plane.d;
  3982. result.m[15] = 1.0;
  3983. result._markAsUpdated();
  3984. };
  3985. /**
  3986. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3987. */
  3988. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3989. result.m[0] = xaxis.x;
  3990. result.m[1] = xaxis.y;
  3991. result.m[2] = xaxis.z;
  3992. result.m[3] = 0.0;
  3993. result.m[4] = yaxis.x;
  3994. result.m[5] = yaxis.y;
  3995. result.m[6] = yaxis.z;
  3996. result.m[7] = 0.0;
  3997. result.m[8] = zaxis.x;
  3998. result.m[9] = zaxis.y;
  3999. result.m[10] = zaxis.z;
  4000. result.m[11] = 0.0;
  4001. result.m[12] = 0.0;
  4002. result.m[13] = 0.0;
  4003. result.m[14] = 0.0;
  4004. result.m[15] = 1.0;
  4005. result._markAsUpdated();
  4006. };
  4007. /**
  4008. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4009. */
  4010. Matrix.FromQuaternionToRef = function (quat, result) {
  4011. var xx = quat.x * quat.x;
  4012. var yy = quat.y * quat.y;
  4013. var zz = quat.z * quat.z;
  4014. var xy = quat.x * quat.y;
  4015. var zw = quat.z * quat.w;
  4016. var zx = quat.z * quat.x;
  4017. var yw = quat.y * quat.w;
  4018. var yz = quat.y * quat.z;
  4019. var xw = quat.x * quat.w;
  4020. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4021. result.m[1] = 2.0 * (xy + zw);
  4022. result.m[2] = 2.0 * (zx - yw);
  4023. result.m[3] = 0.0;
  4024. result.m[4] = 2.0 * (xy - zw);
  4025. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4026. result.m[6] = 2.0 * (yz + xw);
  4027. result.m[7] = 0.0;
  4028. result.m[8] = 2.0 * (zx + yw);
  4029. result.m[9] = 2.0 * (yz - xw);
  4030. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4031. result.m[11] = 0.0;
  4032. result.m[12] = 0.0;
  4033. result.m[13] = 0.0;
  4034. result.m[14] = 0.0;
  4035. result.m[15] = 1.0;
  4036. result._markAsUpdated();
  4037. };
  4038. Matrix._tempQuaternion = new Quaternion();
  4039. Matrix._xAxis = Vector3.Zero();
  4040. Matrix._yAxis = Vector3.Zero();
  4041. Matrix._zAxis = Vector3.Zero();
  4042. Matrix._updateFlagSeed = 0;
  4043. Matrix._identityReadOnly = Matrix.Identity();
  4044. return Matrix;
  4045. }());
  4046. BABYLON.Matrix = Matrix;
  4047. var Plane = /** @class */ (function () {
  4048. /**
  4049. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4050. */
  4051. function Plane(a, b, c, d) {
  4052. this.normal = new Vector3(a, b, c);
  4053. this.d = d;
  4054. }
  4055. /**
  4056. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4057. */
  4058. Plane.prototype.asArray = function () {
  4059. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4060. };
  4061. // Methods
  4062. /**
  4063. * Returns a new plane copied from the current Plane.
  4064. */
  4065. Plane.prototype.clone = function () {
  4066. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4067. };
  4068. /**
  4069. * Returns the string "Plane".
  4070. */
  4071. Plane.prototype.getClassName = function () {
  4072. return "Plane";
  4073. };
  4074. /**
  4075. * Returns the Plane hash code.
  4076. */
  4077. Plane.prototype.getHashCode = function () {
  4078. var hash = this.normal.getHashCode();
  4079. hash = (hash * 397) ^ (this.d || 0);
  4080. return hash;
  4081. };
  4082. /**
  4083. * Normalize the current Plane in place.
  4084. * Returns the updated Plane.
  4085. */
  4086. Plane.prototype.normalize = function () {
  4087. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4088. var magnitude = 0.0;
  4089. if (norm !== 0) {
  4090. magnitude = 1.0 / norm;
  4091. }
  4092. this.normal.x *= magnitude;
  4093. this.normal.y *= magnitude;
  4094. this.normal.z *= magnitude;
  4095. this.d *= magnitude;
  4096. return this;
  4097. };
  4098. /**
  4099. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4100. */
  4101. Plane.prototype.transform = function (transformation) {
  4102. var transposedMatrix = Matrix.Transpose(transformation);
  4103. var x = this.normal.x;
  4104. var y = this.normal.y;
  4105. var z = this.normal.z;
  4106. var d = this.d;
  4107. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4108. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4109. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4110. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4111. return new Plane(normalX, normalY, normalZ, finalD);
  4112. };
  4113. /**
  4114. * Returns the dot product (float) of the point coordinates and the plane normal.
  4115. */
  4116. Plane.prototype.dotCoordinate = function (point) {
  4117. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4118. };
  4119. /**
  4120. * Updates the current Plane from the plane defined by the three passed points.
  4121. * Returns the updated Plane.
  4122. */
  4123. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4124. var x1 = point2.x - point1.x;
  4125. var y1 = point2.y - point1.y;
  4126. var z1 = point2.z - point1.z;
  4127. var x2 = point3.x - point1.x;
  4128. var y2 = point3.y - point1.y;
  4129. var z2 = point3.z - point1.z;
  4130. var yz = (y1 * z2) - (z1 * y2);
  4131. var xz = (z1 * x2) - (x1 * z2);
  4132. var xy = (x1 * y2) - (y1 * x2);
  4133. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4134. var invPyth;
  4135. if (pyth !== 0) {
  4136. invPyth = 1.0 / pyth;
  4137. }
  4138. else {
  4139. invPyth = 0.0;
  4140. }
  4141. this.normal.x = yz * invPyth;
  4142. this.normal.y = xz * invPyth;
  4143. this.normal.z = xy * invPyth;
  4144. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4145. return this;
  4146. };
  4147. /**
  4148. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4149. */
  4150. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4151. var dot = Vector3.Dot(this.normal, direction);
  4152. return (dot <= epsilon);
  4153. };
  4154. /**
  4155. * Returns the signed distance (float) from the passed point to the Plane.
  4156. */
  4157. Plane.prototype.signedDistanceTo = function (point) {
  4158. return Vector3.Dot(point, this.normal) + this.d;
  4159. };
  4160. // Statics
  4161. /**
  4162. * Returns a new Plane from the passed array.
  4163. */
  4164. Plane.FromArray = function (array) {
  4165. return new Plane(array[0], array[1], array[2], array[3]);
  4166. };
  4167. /**
  4168. * Returns a new Plane defined by the three passed points.
  4169. */
  4170. Plane.FromPoints = function (point1, point2, point3) {
  4171. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4172. result.copyFromPoints(point1, point2, point3);
  4173. return result;
  4174. };
  4175. /**
  4176. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4177. * Note : the vector "normal" is updated because normalized.
  4178. */
  4179. Plane.FromPositionAndNormal = function (origin, normal) {
  4180. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4181. normal.normalize();
  4182. result.normal = normal;
  4183. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4184. return result;
  4185. };
  4186. /**
  4187. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4188. */
  4189. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4190. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4191. return Vector3.Dot(point, normal) + d;
  4192. };
  4193. return Plane;
  4194. }());
  4195. BABYLON.Plane = Plane;
  4196. var Viewport = /** @class */ (function () {
  4197. /**
  4198. * Creates a Viewport object located at (x, y) and sized (width, height).
  4199. */
  4200. function Viewport(x, y, width, height) {
  4201. this.x = x;
  4202. this.y = y;
  4203. this.width = width;
  4204. this.height = height;
  4205. }
  4206. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4207. if (renderWidthOrEngine.getRenderWidth) {
  4208. var engine = renderWidthOrEngine;
  4209. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4210. }
  4211. var renderWidth = renderWidthOrEngine;
  4212. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4213. };
  4214. /**
  4215. * Returns a new Viewport copied from the current one.
  4216. */
  4217. Viewport.prototype.clone = function () {
  4218. return new Viewport(this.x, this.y, this.width, this.height);
  4219. };
  4220. return Viewport;
  4221. }());
  4222. BABYLON.Viewport = Viewport;
  4223. var Frustum = /** @class */ (function () {
  4224. function Frustum() {
  4225. }
  4226. /**
  4227. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4228. */
  4229. Frustum.GetPlanes = function (transform) {
  4230. var frustumPlanes = [];
  4231. for (var index = 0; index < 6; index++) {
  4232. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4233. }
  4234. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4235. return frustumPlanes;
  4236. };
  4237. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4238. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4239. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4240. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4241. frustumPlane.d = transform.m[15] + transform.m[14];
  4242. frustumPlane.normalize();
  4243. };
  4244. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4245. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4246. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4247. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4248. frustumPlane.d = transform.m[15] - transform.m[14];
  4249. frustumPlane.normalize();
  4250. };
  4251. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4252. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4253. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4254. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4255. frustumPlane.d = transform.m[15] + transform.m[12];
  4256. frustumPlane.normalize();
  4257. };
  4258. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4259. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4260. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4261. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4262. frustumPlane.d = transform.m[15] - transform.m[12];
  4263. frustumPlane.normalize();
  4264. };
  4265. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4266. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4267. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4268. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4269. frustumPlane.d = transform.m[15] - transform.m[13];
  4270. frustumPlane.normalize();
  4271. };
  4272. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4273. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4274. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4275. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4276. frustumPlane.d = transform.m[15] + transform.m[13];
  4277. frustumPlane.normalize();
  4278. };
  4279. /**
  4280. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4281. */
  4282. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4283. // Near
  4284. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4285. // Far
  4286. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4287. // Left
  4288. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4289. // Right
  4290. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4291. // Top
  4292. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4293. // Bottom
  4294. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4295. };
  4296. return Frustum;
  4297. }());
  4298. BABYLON.Frustum = Frustum;
  4299. var Space;
  4300. (function (Space) {
  4301. Space[Space["LOCAL"] = 0] = "LOCAL";
  4302. Space[Space["WORLD"] = 1] = "WORLD";
  4303. Space[Space["BONE"] = 2] = "BONE";
  4304. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4305. var Axis = /** @class */ (function () {
  4306. function Axis() {
  4307. }
  4308. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4309. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4310. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4311. return Axis;
  4312. }());
  4313. BABYLON.Axis = Axis;
  4314. ;
  4315. var BezierCurve = /** @class */ (function () {
  4316. function BezierCurve() {
  4317. }
  4318. /**
  4319. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4320. */
  4321. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4322. // Extract X (which is equal to time here)
  4323. var f0 = 1 - 3 * x2 + 3 * x1;
  4324. var f1 = 3 * x2 - 6 * x1;
  4325. var f2 = 3 * x1;
  4326. var refinedT = t;
  4327. for (var i = 0; i < 5; i++) {
  4328. var refinedT2 = refinedT * refinedT;
  4329. var refinedT3 = refinedT2 * refinedT;
  4330. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4331. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4332. refinedT -= (x - t) * slope;
  4333. refinedT = Math.min(1, Math.max(0, refinedT));
  4334. }
  4335. // Resolve cubic bezier for the given x
  4336. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4337. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4338. Math.pow(refinedT, 3);
  4339. };
  4340. return BezierCurve;
  4341. }());
  4342. BABYLON.BezierCurve = BezierCurve;
  4343. var Orientation;
  4344. (function (Orientation) {
  4345. Orientation[Orientation["CW"] = 0] = "CW";
  4346. Orientation[Orientation["CCW"] = 1] = "CCW";
  4347. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4348. var Angle = /** @class */ (function () {
  4349. /**
  4350. * Creates an Angle object of "radians" radians (float).
  4351. */
  4352. function Angle(radians) {
  4353. var _this = this;
  4354. /**
  4355. * Returns the Angle value in degrees (float).
  4356. */
  4357. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4358. /**
  4359. * Returns the Angle value in radians (float).
  4360. */
  4361. this.radians = function () { return _this._radians; };
  4362. this._radians = radians;
  4363. if (this._radians < 0.0)
  4364. this._radians += (2.0 * Math.PI);
  4365. }
  4366. /**
  4367. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4368. */
  4369. Angle.BetweenTwoPoints = function (a, b) {
  4370. var delta = b.subtract(a);
  4371. var theta = Math.atan2(delta.y, delta.x);
  4372. return new Angle(theta);
  4373. };
  4374. /**
  4375. * Returns a new Angle object from the passed float in radians.
  4376. */
  4377. Angle.FromRadians = function (radians) {
  4378. return new Angle(radians);
  4379. };
  4380. /**
  4381. * Returns a new Angle object from the passed float in degrees.
  4382. */
  4383. Angle.FromDegrees = function (degrees) {
  4384. return new Angle(degrees * Math.PI / 180.0);
  4385. };
  4386. return Angle;
  4387. }());
  4388. BABYLON.Angle = Angle;
  4389. var Arc2 = /** @class */ (function () {
  4390. /**
  4391. * Creates an Arc object from the three passed points : start, middle and end.
  4392. */
  4393. function Arc2(startPoint, midPoint, endPoint) {
  4394. this.startPoint = startPoint;
  4395. this.midPoint = midPoint;
  4396. this.endPoint = endPoint;
  4397. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4398. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4399. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4400. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4401. 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);
  4402. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4403. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4404. var a1 = this.startAngle.degrees();
  4405. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4406. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4407. // angles correction
  4408. if (a2 - a1 > +180.0)
  4409. a2 -= 360.0;
  4410. if (a2 - a1 < -180.0)
  4411. a2 += 360.0;
  4412. if (a3 - a2 > +180.0)
  4413. a3 -= 360.0;
  4414. if (a3 - a2 < -180.0)
  4415. a3 += 360.0;
  4416. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4417. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4418. }
  4419. return Arc2;
  4420. }());
  4421. BABYLON.Arc2 = Arc2;
  4422. var Path2 = /** @class */ (function () {
  4423. /**
  4424. * Creates a Path2 object from the starting 2D coordinates x and y.
  4425. */
  4426. function Path2(x, y) {
  4427. this._points = new Array();
  4428. this._length = 0.0;
  4429. this.closed = false;
  4430. this._points.push(new Vector2(x, y));
  4431. }
  4432. /**
  4433. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4434. * Returns the updated Path2.
  4435. */
  4436. Path2.prototype.addLineTo = function (x, y) {
  4437. if (closed) {
  4438. //Tools.Error("cannot add lines to closed paths");
  4439. return this;
  4440. }
  4441. var newPoint = new Vector2(x, y);
  4442. var previousPoint = this._points[this._points.length - 1];
  4443. this._points.push(newPoint);
  4444. this._length += newPoint.subtract(previousPoint).length();
  4445. return this;
  4446. };
  4447. /**
  4448. * 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.
  4449. * Returns the updated Path2.
  4450. */
  4451. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4452. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4453. if (closed) {
  4454. //Tools.Error("cannot add arcs to closed paths");
  4455. return this;
  4456. }
  4457. var startPoint = this._points[this._points.length - 1];
  4458. var midPoint = new Vector2(midX, midY);
  4459. var endPoint = new Vector2(endX, endY);
  4460. var arc = new Arc2(startPoint, midPoint, endPoint);
  4461. var increment = arc.angle.radians() / numberOfSegments;
  4462. if (arc.orientation === Orientation.CW)
  4463. increment *= -1;
  4464. var currentAngle = arc.startAngle.radians() + increment;
  4465. for (var i = 0; i < numberOfSegments; i++) {
  4466. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4467. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4468. this.addLineTo(x, y);
  4469. currentAngle += increment;
  4470. }
  4471. return this;
  4472. };
  4473. /**
  4474. * Closes the Path2.
  4475. * Returns the Path2.
  4476. */
  4477. Path2.prototype.close = function () {
  4478. this.closed = true;
  4479. return this;
  4480. };
  4481. /**
  4482. * Returns the Path2 total length (float).
  4483. */
  4484. Path2.prototype.length = function () {
  4485. var result = this._length;
  4486. if (!this.closed) {
  4487. var lastPoint = this._points[this._points.length - 1];
  4488. var firstPoint = this._points[0];
  4489. result += (firstPoint.subtract(lastPoint).length());
  4490. }
  4491. return result;
  4492. };
  4493. /**
  4494. * Returns the Path2 internal array of points.
  4495. */
  4496. Path2.prototype.getPoints = function () {
  4497. return this._points;
  4498. };
  4499. /**
  4500. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4501. */
  4502. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4503. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4504. //Tools.Error("normalized length position should be between 0 and 1.");
  4505. return Vector2.Zero();
  4506. }
  4507. var lengthPosition = normalizedLengthPosition * this.length();
  4508. var previousOffset = 0;
  4509. for (var i = 0; i < this._points.length; i++) {
  4510. var j = (i + 1) % this._points.length;
  4511. var a = this._points[i];
  4512. var b = this._points[j];
  4513. var bToA = b.subtract(a);
  4514. var nextOffset = (bToA.length() + previousOffset);
  4515. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4516. var dir = bToA.normalize();
  4517. var localOffset = lengthPosition - previousOffset;
  4518. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4519. }
  4520. previousOffset = nextOffset;
  4521. }
  4522. //Tools.Error("internal error");
  4523. return Vector2.Zero();
  4524. };
  4525. /**
  4526. * Returns a new Path2 starting at the coordinates (x, y).
  4527. */
  4528. Path2.StartingAt = function (x, y) {
  4529. return new Path2(x, y);
  4530. };
  4531. return Path2;
  4532. }());
  4533. BABYLON.Path2 = Path2;
  4534. var Path3D = /** @class */ (function () {
  4535. /**
  4536. * new Path3D(path, normal, raw)
  4537. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4538. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4539. * path : an array of Vector3, the curve axis of the Path3D
  4540. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4541. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4542. */
  4543. function Path3D(path, firstNormal, raw) {
  4544. if (firstNormal === void 0) { firstNormal = null; }
  4545. this.path = path;
  4546. this._curve = new Array();
  4547. this._distances = new Array();
  4548. this._tangents = new Array();
  4549. this._normals = new Array();
  4550. this._binormals = new Array();
  4551. for (var p = 0; p < path.length; p++) {
  4552. this._curve[p] = path[p].clone(); // hard copy
  4553. }
  4554. this._raw = raw || false;
  4555. this._compute(firstNormal);
  4556. }
  4557. /**
  4558. * Returns the Path3D array of successive Vector3 designing its curve.
  4559. */
  4560. Path3D.prototype.getCurve = function () {
  4561. return this._curve;
  4562. };
  4563. /**
  4564. * Returns an array populated with tangent vectors on each Path3D curve point.
  4565. */
  4566. Path3D.prototype.getTangents = function () {
  4567. return this._tangents;
  4568. };
  4569. /**
  4570. * Returns an array populated with normal vectors on each Path3D curve point.
  4571. */
  4572. Path3D.prototype.getNormals = function () {
  4573. return this._normals;
  4574. };
  4575. /**
  4576. * Returns an array populated with binormal vectors on each Path3D curve point.
  4577. */
  4578. Path3D.prototype.getBinormals = function () {
  4579. return this._binormals;
  4580. };
  4581. /**
  4582. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4583. */
  4584. Path3D.prototype.getDistances = function () {
  4585. return this._distances;
  4586. };
  4587. /**
  4588. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4589. * Returns the same object updated.
  4590. */
  4591. Path3D.prototype.update = function (path, firstNormal) {
  4592. if (firstNormal === void 0) { firstNormal = null; }
  4593. for (var p = 0; p < path.length; p++) {
  4594. this._curve[p].x = path[p].x;
  4595. this._curve[p].y = path[p].y;
  4596. this._curve[p].z = path[p].z;
  4597. }
  4598. this._compute(firstNormal);
  4599. return this;
  4600. };
  4601. // private function compute() : computes tangents, normals and binormals
  4602. Path3D.prototype._compute = function (firstNormal) {
  4603. var l = this._curve.length;
  4604. // first and last tangents
  4605. this._tangents[0] = this._getFirstNonNullVector(0);
  4606. if (!this._raw) {
  4607. this._tangents[0].normalize();
  4608. }
  4609. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4610. if (!this._raw) {
  4611. this._tangents[l - 1].normalize();
  4612. }
  4613. // normals and binormals at first point : arbitrary vector with _normalVector()
  4614. var tg0 = this._tangents[0];
  4615. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4616. this._normals[0] = pp0;
  4617. if (!this._raw) {
  4618. this._normals[0].normalize();
  4619. }
  4620. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4621. if (!this._raw) {
  4622. this._binormals[0].normalize();
  4623. }
  4624. this._distances[0] = 0.0;
  4625. // normals and binormals : next points
  4626. var prev; // previous vector (segment)
  4627. var cur; // current vector (segment)
  4628. var curTang; // current tangent
  4629. // previous normal
  4630. var prevBinor; // previous binormal
  4631. for (var i = 1; i < l; i++) {
  4632. // tangents
  4633. prev = this._getLastNonNullVector(i);
  4634. if (i < l - 1) {
  4635. cur = this._getFirstNonNullVector(i);
  4636. this._tangents[i] = prev.add(cur);
  4637. this._tangents[i].normalize();
  4638. }
  4639. this._distances[i] = this._distances[i - 1] + prev.length();
  4640. // normals and binormals
  4641. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4642. curTang = this._tangents[i];
  4643. prevBinor = this._binormals[i - 1];
  4644. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4645. if (!this._raw) {
  4646. this._normals[i].normalize();
  4647. }
  4648. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4649. if (!this._raw) {
  4650. this._binormals[i].normalize();
  4651. }
  4652. }
  4653. };
  4654. // private function getFirstNonNullVector(index)
  4655. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4656. Path3D.prototype._getFirstNonNullVector = function (index) {
  4657. var i = 1;
  4658. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4659. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4660. i++;
  4661. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4662. }
  4663. return nNVector;
  4664. };
  4665. // private function getLastNonNullVector(index)
  4666. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4667. Path3D.prototype._getLastNonNullVector = function (index) {
  4668. var i = 1;
  4669. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4670. while (nLVector.length() === 0 && index > i + 1) {
  4671. i++;
  4672. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4673. }
  4674. return nLVector;
  4675. };
  4676. // private function normalVector(v0, vt, va) :
  4677. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4678. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4679. Path3D.prototype._normalVector = function (v0, vt, va) {
  4680. var normal0;
  4681. var tgl = vt.length();
  4682. if (tgl === 0.0) {
  4683. tgl = 1.0;
  4684. }
  4685. if (va === undefined || va === null) {
  4686. var point;
  4687. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4688. point = new Vector3(0.0, -1.0, 0.0);
  4689. }
  4690. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4691. point = new Vector3(1.0, 0.0, 0.0);
  4692. }
  4693. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4694. point = new Vector3(0.0, 0.0, 1.0);
  4695. }
  4696. else {
  4697. point = Vector3.Zero();
  4698. }
  4699. normal0 = Vector3.Cross(vt, point);
  4700. }
  4701. else {
  4702. normal0 = Vector3.Cross(vt, va);
  4703. Vector3.CrossToRef(normal0, vt, normal0);
  4704. }
  4705. normal0.normalize();
  4706. return normal0;
  4707. };
  4708. return Path3D;
  4709. }());
  4710. BABYLON.Path3D = Path3D;
  4711. var Curve3 = /** @class */ (function () {
  4712. /**
  4713. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4714. * A Curve3 is designed from a series of successive Vector3.
  4715. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4716. */
  4717. function Curve3(points) {
  4718. this._length = 0.0;
  4719. this._points = points;
  4720. this._length = this._computeLength(points);
  4721. }
  4722. /**
  4723. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4724. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4725. * @param v1 (Vector3) the control point
  4726. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4727. * @param nbPoints (integer) the wanted number of points in the curve
  4728. */
  4729. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4730. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4731. var bez = new Array();
  4732. var equation = function (t, val0, val1, val2) {
  4733. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4734. return res;
  4735. };
  4736. for (var i = 0; i <= nbPoints; i++) {
  4737. 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)));
  4738. }
  4739. return new Curve3(bez);
  4740. };
  4741. /**
  4742. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4743. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4744. * @param v1 (Vector3) the first control point
  4745. * @param v2 (Vector3) the second control point
  4746. * @param v3 (Vector3) the end point of the Cubic Bezier
  4747. * @param nbPoints (integer) the wanted number of points in the curve
  4748. */
  4749. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4750. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4751. var bez = new Array();
  4752. var equation = function (t, val0, val1, val2, val3) {
  4753. 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;
  4754. return res;
  4755. };
  4756. for (var i = 0; i <= nbPoints; i++) {
  4757. 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)));
  4758. }
  4759. return new Curve3(bez);
  4760. };
  4761. /**
  4762. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4763. * @param p1 (Vector3) the origin point of the Hermite Spline
  4764. * @param t1 (Vector3) the tangent vector at the origin point
  4765. * @param p2 (Vector3) the end point of the Hermite Spline
  4766. * @param t2 (Vector3) the tangent vector at the end point
  4767. * @param nbPoints (integer) the wanted number of points in the curve
  4768. */
  4769. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4770. var hermite = new Array();
  4771. var step = 1.0 / nbPoints;
  4772. for (var i = 0; i <= nbPoints; i++) {
  4773. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4774. }
  4775. return new Curve3(hermite);
  4776. };
  4777. /**
  4778. * Returns a Curve3 object along a CatmullRom Spline curve :
  4779. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4780. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4781. */
  4782. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4783. var totalPoints = new Array();
  4784. totalPoints.push(points[0].clone());
  4785. Array.prototype.push.apply(totalPoints, points);
  4786. totalPoints.push(points[points.length - 1].clone());
  4787. var catmullRom = new Array();
  4788. var step = 1.0 / nbPoints;
  4789. var amount = 0.0;
  4790. for (var i = 0; i < totalPoints.length - 3; i++) {
  4791. amount = 0;
  4792. for (var c = 0; c < nbPoints; c++) {
  4793. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4794. amount += step;
  4795. }
  4796. }
  4797. i--;
  4798. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4799. return new Curve3(catmullRom);
  4800. };
  4801. /**
  4802. * Returns the Curve3 stored array of successive Vector3
  4803. */
  4804. Curve3.prototype.getPoints = function () {
  4805. return this._points;
  4806. };
  4807. /**
  4808. * Returns the computed length (float) of the curve.
  4809. */
  4810. Curve3.prototype.length = function () {
  4811. return this._length;
  4812. };
  4813. /**
  4814. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4815. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4816. * curveA and curveB keep unchanged.
  4817. */
  4818. Curve3.prototype.continue = function (curve) {
  4819. var lastPoint = this._points[this._points.length - 1];
  4820. var continuedPoints = this._points.slice();
  4821. var curvePoints = curve.getPoints();
  4822. for (var i = 1; i < curvePoints.length; i++) {
  4823. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4824. }
  4825. var continuedCurve = new Curve3(continuedPoints);
  4826. return continuedCurve;
  4827. };
  4828. Curve3.prototype._computeLength = function (path) {
  4829. var l = 0;
  4830. for (var i = 1; i < path.length; i++) {
  4831. l += (path[i].subtract(path[i - 1])).length();
  4832. }
  4833. return l;
  4834. };
  4835. return Curve3;
  4836. }());
  4837. BABYLON.Curve3 = Curve3;
  4838. // Vertex formats
  4839. var PositionNormalVertex = /** @class */ (function () {
  4840. function PositionNormalVertex(position, normal) {
  4841. if (position === void 0) { position = Vector3.Zero(); }
  4842. if (normal === void 0) { normal = Vector3.Up(); }
  4843. this.position = position;
  4844. this.normal = normal;
  4845. }
  4846. PositionNormalVertex.prototype.clone = function () {
  4847. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4848. };
  4849. return PositionNormalVertex;
  4850. }());
  4851. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4852. var PositionNormalTextureVertex = /** @class */ (function () {
  4853. function PositionNormalTextureVertex(position, normal, uv) {
  4854. if (position === void 0) { position = Vector3.Zero(); }
  4855. if (normal === void 0) { normal = Vector3.Up(); }
  4856. if (uv === void 0) { uv = Vector2.Zero(); }
  4857. this.position = position;
  4858. this.normal = normal;
  4859. this.uv = uv;
  4860. }
  4861. PositionNormalTextureVertex.prototype.clone = function () {
  4862. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4863. };
  4864. return PositionNormalTextureVertex;
  4865. }());
  4866. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4867. // Temporary pre-allocated objects for engine internal use
  4868. // usage in any internal function :
  4869. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4870. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4871. var Tmp = /** @class */ (function () {
  4872. function Tmp() {
  4873. }
  4874. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4875. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4876. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4877. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4878. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4879. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4880. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4881. Matrix.Zero(), Matrix.Zero(),
  4882. Matrix.Zero(), Matrix.Zero(),
  4883. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4884. return Tmp;
  4885. }());
  4886. BABYLON.Tmp = Tmp;
  4887. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4888. var MathTmp = /** @class */ (function () {
  4889. function MathTmp() {
  4890. }
  4891. MathTmp.Vector3 = [Vector3.Zero()];
  4892. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4893. MathTmp.Quaternion = [Quaternion.Zero()];
  4894. return MathTmp;
  4895. }());
  4896. })(BABYLON || (BABYLON = {}));
  4897. //# sourceMappingURL=babylon.math.js.map
  4898. var BABYLON;
  4899. (function (BABYLON) {
  4900. var Scalar = /** @class */ (function () {
  4901. function Scalar() {
  4902. }
  4903. /**
  4904. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4905. */
  4906. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4907. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4908. var num = a - b;
  4909. return -epsilon <= num && num <= epsilon;
  4910. };
  4911. /**
  4912. * Returns a string : the upper case translation of the number i to hexadecimal.
  4913. */
  4914. Scalar.ToHex = function (i) {
  4915. var str = i.toString(16);
  4916. if (i <= 15) {
  4917. return ("0" + str).toUpperCase();
  4918. }
  4919. return str.toUpperCase();
  4920. };
  4921. /**
  4922. * Returns -1 if value is negative and +1 is value is positive.
  4923. * Returns the value itself if it's equal to zero.
  4924. */
  4925. Scalar.Sign = function (value) {
  4926. value = +value; // convert to a number
  4927. if (value === 0 || isNaN(value))
  4928. return value;
  4929. return value > 0 ? 1 : -1;
  4930. };
  4931. /**
  4932. * Returns the value itself if it's between min and max.
  4933. * Returns min if the value is lower than min.
  4934. * Returns max if the value is greater than max.
  4935. */
  4936. Scalar.Clamp = function (value, min, max) {
  4937. if (min === void 0) { min = 0; }
  4938. if (max === void 0) { max = 1; }
  4939. return Math.min(max, Math.max(min, value));
  4940. };
  4941. /**
  4942. * Returns the log2 of value.
  4943. */
  4944. Scalar.Log2 = function (value) {
  4945. return Math.log(value) * Math.LOG2E;
  4946. };
  4947. /**
  4948. * Loops the value, so that it is never larger than length and never smaller than 0.
  4949. *
  4950. * This is similar to the modulo operator but it works with floating point numbers.
  4951. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4952. * With t = 5 and length = 2.5, the result would be 0.0.
  4953. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4954. */
  4955. Scalar.Repeat = function (value, length) {
  4956. return value - Math.floor(value / length) * length;
  4957. };
  4958. /**
  4959. * Normalize the value between 0.0 and 1.0 using min and max values
  4960. */
  4961. Scalar.Normalize = function (value, min, max) {
  4962. return (value - min) / (max - min);
  4963. };
  4964. /**
  4965. * Denormalize the value from 0.0 and 1.0 using min and max values
  4966. */
  4967. Scalar.Denormalize = function (normalized, min, max) {
  4968. return (normalized * (max - min) + min);
  4969. };
  4970. /**
  4971. * Calculates the shortest difference between two given angles given in degrees.
  4972. */
  4973. Scalar.DeltaAngle = function (current, target) {
  4974. var num = Scalar.Repeat(target - current, 360.0);
  4975. if (num > 180.0) {
  4976. num -= 360.0;
  4977. }
  4978. return num;
  4979. };
  4980. /**
  4981. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4982. *
  4983. * The returned value will move back and forth between 0 and length
  4984. */
  4985. Scalar.PingPong = function (tx, length) {
  4986. var t = Scalar.Repeat(tx, length * 2.0);
  4987. return length - Math.abs(t - length);
  4988. };
  4989. /**
  4990. * Interpolates between min and max with smoothing at the limits.
  4991. *
  4992. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4993. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4994. */
  4995. Scalar.SmoothStep = function (from, to, tx) {
  4996. var t = Scalar.Clamp(tx);
  4997. t = -2.0 * t * t * t + 3.0 * t * t;
  4998. return to * t + from * (1.0 - t);
  4999. };
  5000. /**
  5001. * Moves a value current towards target.
  5002. *
  5003. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5004. * Negative values of maxDelta pushes the value away from target.
  5005. */
  5006. Scalar.MoveTowards = function (current, target, maxDelta) {
  5007. var result = 0;
  5008. if (Math.abs(target - current) <= maxDelta) {
  5009. result = target;
  5010. }
  5011. else {
  5012. result = current + Scalar.Sign(target - current) * maxDelta;
  5013. }
  5014. return result;
  5015. };
  5016. /**
  5017. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5018. *
  5019. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5020. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5021. */
  5022. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5023. var num = Scalar.DeltaAngle(current, target);
  5024. var result = 0;
  5025. if (-maxDelta < num && num < maxDelta) {
  5026. result = target;
  5027. }
  5028. else {
  5029. target = current + num;
  5030. result = Scalar.MoveTowards(current, target, maxDelta);
  5031. }
  5032. return result;
  5033. };
  5034. /**
  5035. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5036. */
  5037. Scalar.Lerp = function (start, end, amount) {
  5038. return start + ((end - start) * amount);
  5039. };
  5040. /**
  5041. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5042. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5043. */
  5044. Scalar.LerpAngle = function (start, end, amount) {
  5045. var num = Scalar.Repeat(end - start, 360.0);
  5046. if (num > 180.0) {
  5047. num -= 360.0;
  5048. }
  5049. return start + num * Scalar.Clamp(amount);
  5050. };
  5051. /**
  5052. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5053. */
  5054. Scalar.InverseLerp = function (a, b, value) {
  5055. var result = 0;
  5056. if (a != b) {
  5057. result = Scalar.Clamp((value - a) / (b - a));
  5058. }
  5059. else {
  5060. result = 0.0;
  5061. }
  5062. return result;
  5063. };
  5064. /**
  5065. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5066. */
  5067. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5068. var squared = amount * amount;
  5069. var cubed = amount * squared;
  5070. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5071. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5072. var part3 = (cubed - (2.0 * squared)) + amount;
  5073. var part4 = cubed - squared;
  5074. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5075. };
  5076. /**
  5077. * Returns a random float number between and min and max values
  5078. */
  5079. Scalar.RandomRange = function (min, max) {
  5080. if (min === max)
  5081. return min;
  5082. return ((Math.random() * (max - min)) + min);
  5083. };
  5084. /**
  5085. * This function returns percentage of a number in a given range.
  5086. *
  5087. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5088. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5089. */
  5090. Scalar.RangeToPercent = function (number, min, max) {
  5091. return ((number - min) / (max - min));
  5092. };
  5093. /**
  5094. * This function returns number that corresponds to the percentage in a given range.
  5095. *
  5096. * PercentToRange(0.34,0,100) will return 34.
  5097. */
  5098. Scalar.PercentToRange = function (percent, min, max) {
  5099. return ((max - min) * percent + min);
  5100. };
  5101. return Scalar;
  5102. }());
  5103. BABYLON.Scalar = Scalar;
  5104. })(BABYLON || (BABYLON = {}));
  5105. //# sourceMappingURL=babylon.math.scalar.js.map
  5106. //# sourceMappingURL=babylon.mixins.js.map
  5107. var BABYLON;
  5108. (function (BABYLON) {
  5109. var __decoratorInitialStore = {};
  5110. var __mergedStore = {};
  5111. var _copySource = function (creationFunction, source, instanciate) {
  5112. var destination = creationFunction();
  5113. // Tags
  5114. if (BABYLON.Tags) {
  5115. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5116. }
  5117. var classStore = getMergedStore(destination);
  5118. // Properties
  5119. for (var property in classStore) {
  5120. var propertyDescriptor = classStore[property];
  5121. var sourceProperty = source[property];
  5122. var propertyType = propertyDescriptor.type;
  5123. if (sourceProperty !== undefined && sourceProperty !== null) {
  5124. switch (propertyType) {
  5125. case 0: // Value
  5126. case 6:// Mesh reference
  5127. destination[property] = sourceProperty;
  5128. break;
  5129. case 1:// Texture
  5130. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5131. break;
  5132. case 2: // Color3
  5133. case 3: // FresnelParameters
  5134. case 4: // Vector2
  5135. case 5: // Vector3
  5136. case 7:// Color Curves
  5137. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5138. break;
  5139. }
  5140. }
  5141. }
  5142. return destination;
  5143. };
  5144. function getDirectStore(target) {
  5145. var classKey = target.getClassName();
  5146. if (!__decoratorInitialStore[classKey]) {
  5147. __decoratorInitialStore[classKey] = {};
  5148. }
  5149. return __decoratorInitialStore[classKey];
  5150. }
  5151. /**
  5152. * Return the list of properties flagged as serializable
  5153. * @param target: host object
  5154. */
  5155. function getMergedStore(target) {
  5156. var classKey = target.getClassName();
  5157. if (__mergedStore[classKey]) {
  5158. return __mergedStore[classKey];
  5159. }
  5160. __mergedStore[classKey] = {};
  5161. var store = __mergedStore[classKey];
  5162. var currentTarget = target;
  5163. var currentKey = classKey;
  5164. while (currentKey) {
  5165. var initialStore = __decoratorInitialStore[currentKey];
  5166. for (var property in initialStore) {
  5167. store[property] = initialStore[property];
  5168. }
  5169. var parent_1 = void 0;
  5170. var done = false;
  5171. do {
  5172. parent_1 = Object.getPrototypeOf(currentTarget);
  5173. if (!parent_1.getClassName) {
  5174. done = true;
  5175. break;
  5176. }
  5177. if (parent_1.getClassName() !== currentKey) {
  5178. break;
  5179. }
  5180. currentTarget = parent_1;
  5181. } while (parent_1);
  5182. if (done) {
  5183. break;
  5184. }
  5185. currentKey = parent_1.getClassName();
  5186. currentTarget = parent_1;
  5187. }
  5188. return store;
  5189. }
  5190. function generateSerializableMember(type, sourceName) {
  5191. return function (target, propertyKey) {
  5192. var classStore = getDirectStore(target);
  5193. if (!classStore[propertyKey]) {
  5194. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5195. }
  5196. };
  5197. }
  5198. function generateExpandMember(setCallback, targetKey) {
  5199. if (targetKey === void 0) { targetKey = null; }
  5200. return function (target, propertyKey) {
  5201. var key = targetKey || ("_" + propertyKey);
  5202. Object.defineProperty(target, propertyKey, {
  5203. get: function () {
  5204. return this[key];
  5205. },
  5206. set: function (value) {
  5207. if (this[key] === value) {
  5208. return;
  5209. }
  5210. this[key] = value;
  5211. target[setCallback].apply(this);
  5212. },
  5213. enumerable: true,
  5214. configurable: true
  5215. });
  5216. };
  5217. }
  5218. function expandToProperty(callback, targetKey) {
  5219. if (targetKey === void 0) { targetKey = null; }
  5220. return generateExpandMember(callback, targetKey);
  5221. }
  5222. BABYLON.expandToProperty = expandToProperty;
  5223. function serialize(sourceName) {
  5224. return generateSerializableMember(0, sourceName); // value member
  5225. }
  5226. BABYLON.serialize = serialize;
  5227. function serializeAsTexture(sourceName) {
  5228. return generateSerializableMember(1, sourceName); // texture member
  5229. }
  5230. BABYLON.serializeAsTexture = serializeAsTexture;
  5231. function serializeAsColor3(sourceName) {
  5232. return generateSerializableMember(2, sourceName); // color3 member
  5233. }
  5234. BABYLON.serializeAsColor3 = serializeAsColor3;
  5235. function serializeAsFresnelParameters(sourceName) {
  5236. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5237. }
  5238. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5239. function serializeAsVector2(sourceName) {
  5240. return generateSerializableMember(4, sourceName); // vector2 member
  5241. }
  5242. BABYLON.serializeAsVector2 = serializeAsVector2;
  5243. function serializeAsVector3(sourceName) {
  5244. return generateSerializableMember(5, sourceName); // vector3 member
  5245. }
  5246. BABYLON.serializeAsVector3 = serializeAsVector3;
  5247. function serializeAsMeshReference(sourceName) {
  5248. return generateSerializableMember(6, sourceName); // mesh reference member
  5249. }
  5250. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5251. function serializeAsColorCurves(sourceName) {
  5252. return generateSerializableMember(7, sourceName); // color curves
  5253. }
  5254. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5255. function serializeAsColor4(sourceName) {
  5256. return generateSerializableMember(8, sourceName); // color 4
  5257. }
  5258. BABYLON.serializeAsColor4 = serializeAsColor4;
  5259. function serializeAsImageProcessingConfiguration(sourceName) {
  5260. return generateSerializableMember(9, sourceName); // image processing
  5261. }
  5262. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5263. var SerializationHelper = /** @class */ (function () {
  5264. function SerializationHelper() {
  5265. }
  5266. SerializationHelper.Serialize = function (entity, serializationObject) {
  5267. if (!serializationObject) {
  5268. serializationObject = {};
  5269. }
  5270. // Tags
  5271. if (BABYLON.Tags) {
  5272. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5273. }
  5274. var serializedProperties = getMergedStore(entity);
  5275. // Properties
  5276. for (var property in serializedProperties) {
  5277. var propertyDescriptor = serializedProperties[property];
  5278. var targetPropertyName = propertyDescriptor.sourceName || property;
  5279. var propertyType = propertyDescriptor.type;
  5280. var sourceProperty = entity[property];
  5281. if (sourceProperty !== undefined && sourceProperty !== null) {
  5282. switch (propertyType) {
  5283. case 0:// Value
  5284. serializationObject[targetPropertyName] = sourceProperty;
  5285. break;
  5286. case 1:// Texture
  5287. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5288. break;
  5289. case 2:// Color3
  5290. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5291. break;
  5292. case 3:// FresnelParameters
  5293. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5294. break;
  5295. case 4:// Vector2
  5296. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5297. break;
  5298. case 5:// Vector3
  5299. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5300. break;
  5301. case 6:// Mesh reference
  5302. serializationObject[targetPropertyName] = sourceProperty.id;
  5303. break;
  5304. case 7:// Color Curves
  5305. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5306. break;
  5307. case 8:// Color 4
  5308. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5309. break;
  5310. case 9:// Image Processing
  5311. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5312. break;
  5313. }
  5314. }
  5315. }
  5316. return serializationObject;
  5317. };
  5318. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5319. if (rootUrl === void 0) { rootUrl = null; }
  5320. var destination = creationFunction();
  5321. if (!rootUrl) {
  5322. rootUrl = "";
  5323. }
  5324. // Tags
  5325. if (BABYLON.Tags) {
  5326. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5327. }
  5328. var classStore = getMergedStore(destination);
  5329. // Properties
  5330. for (var property in classStore) {
  5331. var propertyDescriptor = classStore[property];
  5332. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5333. var propertyType = propertyDescriptor.type;
  5334. if (sourceProperty !== undefined && sourceProperty !== null) {
  5335. var dest = destination;
  5336. switch (propertyType) {
  5337. case 0:// Value
  5338. dest[property] = sourceProperty;
  5339. break;
  5340. case 1:// Texture
  5341. if (scene) {
  5342. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5343. }
  5344. break;
  5345. case 2:// Color3
  5346. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5347. break;
  5348. case 3:// FresnelParameters
  5349. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5350. break;
  5351. case 4:// Vector2
  5352. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5353. break;
  5354. case 5:// Vector3
  5355. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5356. break;
  5357. case 6:// Mesh reference
  5358. if (scene) {
  5359. dest[property] = scene.getLastMeshByID(sourceProperty);
  5360. }
  5361. break;
  5362. case 7:// Color Curves
  5363. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5364. break;
  5365. case 8:// Color 4
  5366. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5367. break;
  5368. case 9:// Image Processing
  5369. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5370. break;
  5371. }
  5372. }
  5373. }
  5374. return destination;
  5375. };
  5376. SerializationHelper.Clone = function (creationFunction, source) {
  5377. return _copySource(creationFunction, source, false);
  5378. };
  5379. SerializationHelper.Instanciate = function (creationFunction, source) {
  5380. return _copySource(creationFunction, source, true);
  5381. };
  5382. return SerializationHelper;
  5383. }());
  5384. BABYLON.SerializationHelper = SerializationHelper;
  5385. })(BABYLON || (BABYLON = {}));
  5386. //# sourceMappingURL=babylon.decorators.js.map
  5387. var BABYLON;
  5388. (function (BABYLON) {
  5389. /**
  5390. * A class serves as a medium between the observable and its observers
  5391. */
  5392. var EventState = /** @class */ (function () {
  5393. /**
  5394. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5395. */
  5396. function EventState(mask, skipNextObservers, target, currentTarget) {
  5397. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5398. this.initalize(mask, skipNextObservers, target, currentTarget);
  5399. }
  5400. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5401. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5402. this.mask = mask;
  5403. this.skipNextObservers = skipNextObservers;
  5404. this.target = target;
  5405. this.currentTarget = currentTarget;
  5406. return this;
  5407. };
  5408. return EventState;
  5409. }());
  5410. BABYLON.EventState = EventState;
  5411. /**
  5412. * Represent an Observer registered to a given Observable object.
  5413. */
  5414. var Observer = /** @class */ (function () {
  5415. function Observer(callback, mask, scope) {
  5416. if (scope === void 0) { scope = null; }
  5417. this.callback = callback;
  5418. this.mask = mask;
  5419. this.scope = scope;
  5420. }
  5421. return Observer;
  5422. }());
  5423. BABYLON.Observer = Observer;
  5424. /**
  5425. * Represent a list of observers registered to multiple Observables object.
  5426. */
  5427. var MultiObserver = /** @class */ (function () {
  5428. function MultiObserver() {
  5429. }
  5430. MultiObserver.prototype.dispose = function () {
  5431. if (this._observers && this._observables) {
  5432. for (var index = 0; index < this._observers.length; index++) {
  5433. this._observables[index].remove(this._observers[index]);
  5434. }
  5435. }
  5436. this._observers = null;
  5437. this._observables = null;
  5438. };
  5439. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5440. if (mask === void 0) { mask = -1; }
  5441. if (scope === void 0) { scope = null; }
  5442. var result = new MultiObserver();
  5443. result._observers = new Array();
  5444. result._observables = observables;
  5445. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5446. var observable = observables_1[_i];
  5447. var observer = observable.add(callback, mask, false, scope);
  5448. if (observer) {
  5449. result._observers.push(observer);
  5450. }
  5451. }
  5452. return result;
  5453. };
  5454. return MultiObserver;
  5455. }());
  5456. BABYLON.MultiObserver = MultiObserver;
  5457. /**
  5458. * The Observable class is a simple implementation of the Observable pattern.
  5459. * 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.
  5460. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5461. * 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).
  5462. * 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.
  5463. */
  5464. var Observable = /** @class */ (function () {
  5465. function Observable(onObserverAdded) {
  5466. this._observers = new Array();
  5467. this._eventState = new EventState(0);
  5468. if (onObserverAdded) {
  5469. this._onObserverAdded = onObserverAdded;
  5470. }
  5471. }
  5472. /**
  5473. * Create a new Observer with the specified callback
  5474. * @param callback the callback that will be executed for that Observer
  5475. * @param mask the mask used to filter observers
  5476. * @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.
  5477. * @param scope optional scope for the callback to be called from
  5478. */
  5479. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5480. if (mask === void 0) { mask = -1; }
  5481. if (insertFirst === void 0) { insertFirst = false; }
  5482. if (scope === void 0) { scope = null; }
  5483. if (!callback) {
  5484. return null;
  5485. }
  5486. var observer = new Observer(callback, mask, scope);
  5487. if (insertFirst) {
  5488. this._observers.unshift(observer);
  5489. }
  5490. else {
  5491. this._observers.push(observer);
  5492. }
  5493. if (this._onObserverAdded) {
  5494. this._onObserverAdded(observer);
  5495. }
  5496. return observer;
  5497. };
  5498. /**
  5499. * Remove an Observer from the Observable object
  5500. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5501. */
  5502. Observable.prototype.remove = function (observer) {
  5503. if (!observer) {
  5504. return false;
  5505. }
  5506. var index = this._observers.indexOf(observer);
  5507. if (index !== -1) {
  5508. this._observers.splice(index, 1);
  5509. return true;
  5510. }
  5511. return false;
  5512. };
  5513. /**
  5514. * Remove a callback from the Observable object
  5515. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5516. */
  5517. Observable.prototype.removeCallback = function (callback) {
  5518. for (var index = 0; index < this._observers.length; index++) {
  5519. if (this._observers[index].callback === callback) {
  5520. this._observers.splice(index, 1);
  5521. return true;
  5522. }
  5523. }
  5524. return false;
  5525. };
  5526. /**
  5527. * Notify all Observers by calling their respective callback with the given data
  5528. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5529. * @param eventData
  5530. * @param mask
  5531. */
  5532. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5533. if (mask === void 0) { mask = -1; }
  5534. if (!this._observers.length) {
  5535. return true;
  5536. }
  5537. var state = this._eventState;
  5538. state.mask = mask;
  5539. state.target = target;
  5540. state.currentTarget = currentTarget;
  5541. state.skipNextObservers = false;
  5542. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5543. var obs = _a[_i];
  5544. if (obs.mask & mask) {
  5545. if (obs.scope) {
  5546. obs.callback.apply(obs.scope, [eventData, state]);
  5547. }
  5548. else {
  5549. obs.callback(eventData, state);
  5550. }
  5551. }
  5552. if (state.skipNextObservers) {
  5553. return false;
  5554. }
  5555. }
  5556. return true;
  5557. };
  5558. /**
  5559. * Notify a specific observer
  5560. * @param eventData
  5561. * @param mask
  5562. */
  5563. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5564. if (mask === void 0) { mask = -1; }
  5565. var state = this._eventState;
  5566. state.mask = mask;
  5567. state.skipNextObservers = false;
  5568. observer.callback(eventData, state);
  5569. };
  5570. /**
  5571. * return true is the Observable has at least one Observer registered
  5572. */
  5573. Observable.prototype.hasObservers = function () {
  5574. return this._observers.length > 0;
  5575. };
  5576. /**
  5577. * Clear the list of observers
  5578. */
  5579. Observable.prototype.clear = function () {
  5580. this._observers = new Array();
  5581. this._onObserverAdded = null;
  5582. };
  5583. /**
  5584. * Clone the current observable
  5585. */
  5586. Observable.prototype.clone = function () {
  5587. var result = new Observable();
  5588. result._observers = this._observers.slice(0);
  5589. return result;
  5590. };
  5591. /**
  5592. * Does this observable handles observer registered with a given mask
  5593. * @param {number} trigger - the mask to be tested
  5594. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5595. **/
  5596. Observable.prototype.hasSpecificMask = function (mask) {
  5597. if (mask === void 0) { mask = -1; }
  5598. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5599. var obs = _a[_i];
  5600. if (obs.mask & mask || obs.mask === mask) {
  5601. return true;
  5602. }
  5603. }
  5604. return false;
  5605. };
  5606. return Observable;
  5607. }());
  5608. BABYLON.Observable = Observable;
  5609. })(BABYLON || (BABYLON = {}));
  5610. //# sourceMappingURL=babylon.observable.js.map
  5611. var BABYLON;
  5612. (function (BABYLON) {
  5613. var SmartArray = /** @class */ (function () {
  5614. function SmartArray(capacity) {
  5615. this.length = 0;
  5616. this._duplicateId = 0;
  5617. this.data = new Array(capacity);
  5618. this._id = SmartArray._GlobalId++;
  5619. }
  5620. SmartArray.prototype.push = function (value) {
  5621. this.data[this.length++] = value;
  5622. if (this.length > this.data.length) {
  5623. this.data.length *= 2;
  5624. }
  5625. if (!value.__smartArrayFlags) {
  5626. value.__smartArrayFlags = {};
  5627. }
  5628. value.__smartArrayFlags[this._id] = this._duplicateId;
  5629. };
  5630. SmartArray.prototype.forEach = function (func) {
  5631. for (var index = 0; index < this.length; index++) {
  5632. func(this.data[index]);
  5633. }
  5634. };
  5635. SmartArray.prototype.pushNoDuplicate = function (value) {
  5636. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5637. return false;
  5638. }
  5639. this.push(value);
  5640. return true;
  5641. };
  5642. SmartArray.prototype.sort = function (compareFn) {
  5643. this.data.sort(compareFn);
  5644. };
  5645. SmartArray.prototype.reset = function () {
  5646. this.length = 0;
  5647. this._duplicateId++;
  5648. };
  5649. SmartArray.prototype.dispose = function () {
  5650. this.reset();
  5651. if (this.data) {
  5652. this.data.length = 0;
  5653. this.data = [];
  5654. }
  5655. };
  5656. SmartArray.prototype.concat = function (array) {
  5657. if (array.length === 0) {
  5658. return;
  5659. }
  5660. if (this.length + array.length > this.data.length) {
  5661. this.data.length = (this.length + array.length) * 2;
  5662. }
  5663. for (var index = 0; index < array.length; index++) {
  5664. this.data[this.length++] = (array.data || array)[index];
  5665. }
  5666. };
  5667. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5668. if (array.length === 0) {
  5669. return;
  5670. }
  5671. if (this.length + array.length > this.data.length) {
  5672. this.data.length = (this.length + array.length) * 2;
  5673. }
  5674. for (var index = 0; index < array.length; index++) {
  5675. var item = (array.data || array)[index];
  5676. this.pushNoDuplicate(item);
  5677. }
  5678. };
  5679. SmartArray.prototype.indexOf = function (value) {
  5680. var position = this.data.indexOf(value);
  5681. if (position >= this.length) {
  5682. return -1;
  5683. }
  5684. return position;
  5685. };
  5686. SmartArray.prototype.contains = function (value) {
  5687. return this.data.indexOf(value) !== -1;
  5688. };
  5689. // Statics
  5690. SmartArray._GlobalId = 0;
  5691. return SmartArray;
  5692. }());
  5693. BABYLON.SmartArray = SmartArray;
  5694. })(BABYLON || (BABYLON = {}));
  5695. //# sourceMappingURL=babylon.smartArray.js.map
  5696. var BABYLON;
  5697. (function (BABYLON) {
  5698. // Screenshots
  5699. var screenshotCanvas;
  5700. var cloneValue = function (source, destinationObject) {
  5701. if (!source)
  5702. return null;
  5703. if (source instanceof BABYLON.Mesh) {
  5704. return null;
  5705. }
  5706. if (source instanceof BABYLON.SubMesh) {
  5707. return source.clone(destinationObject);
  5708. }
  5709. else if (source.clone) {
  5710. return source.clone();
  5711. }
  5712. return null;
  5713. };
  5714. var Tools = /** @class */ (function () {
  5715. function Tools() {
  5716. }
  5717. ;
  5718. /**
  5719. * Interpolates between a and b via alpha
  5720. * @param a The lower value (returned when alpha = 0)
  5721. * @param b The upper value (returned when alpha = 1)
  5722. * @param alpha The interpolation-factor
  5723. * @return The mixed value
  5724. */
  5725. Tools.Mix = function (a, b, alpha) {
  5726. return a * (1 - alpha) + b * alpha;
  5727. };
  5728. Tools.Instantiate = function (className) {
  5729. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5730. return Tools.RegisteredExternalClasses[className];
  5731. }
  5732. var arr = className.split(".");
  5733. var fn = (window || this);
  5734. for (var i = 0, len = arr.length; i < len; i++) {
  5735. fn = fn[arr[i]];
  5736. }
  5737. if (typeof fn !== "function") {
  5738. return null;
  5739. }
  5740. return fn;
  5741. };
  5742. Tools.SetImmediate = function (action) {
  5743. if (window.setImmediate) {
  5744. window.setImmediate(action);
  5745. }
  5746. else {
  5747. setTimeout(action, 1);
  5748. }
  5749. };
  5750. Tools.IsExponentOfTwo = function (value) {
  5751. var count = 1;
  5752. do {
  5753. count *= 2;
  5754. } while (count < value);
  5755. return count === value;
  5756. };
  5757. /**
  5758. * Find the next highest power of two.
  5759. * @param x Number to start search from.
  5760. * @return Next highest power of two.
  5761. */
  5762. Tools.CeilingPOT = function (x) {
  5763. x--;
  5764. x |= x >> 1;
  5765. x |= x >> 2;
  5766. x |= x >> 4;
  5767. x |= x >> 8;
  5768. x |= x >> 16;
  5769. x++;
  5770. return x;
  5771. };
  5772. /**
  5773. * Find the next lowest power of two.
  5774. * @param x Number to start search from.
  5775. * @return Next lowest power of two.
  5776. */
  5777. Tools.FloorPOT = function (x) {
  5778. x = x | (x >> 1);
  5779. x = x | (x >> 2);
  5780. x = x | (x >> 4);
  5781. x = x | (x >> 8);
  5782. x = x | (x >> 16);
  5783. return x - (x >> 1);
  5784. };
  5785. /**
  5786. * Find the nearest power of two.
  5787. * @param x Number to start search from.
  5788. * @return Next nearest power of two.
  5789. */
  5790. Tools.NearestPOT = function (x) {
  5791. var c = Tools.CeilingPOT(x);
  5792. var f = Tools.FloorPOT(x);
  5793. return (c - x) > (x - f) ? f : c;
  5794. };
  5795. Tools.GetExponentOfTwo = function (value, max, mode) {
  5796. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5797. var pot;
  5798. switch (mode) {
  5799. case BABYLON.Engine.SCALEMODE_FLOOR:
  5800. pot = Tools.FloorPOT(value);
  5801. break;
  5802. case BABYLON.Engine.SCALEMODE_NEAREST:
  5803. pot = Tools.NearestPOT(value);
  5804. break;
  5805. case BABYLON.Engine.SCALEMODE_CEILING:
  5806. default:
  5807. pot = Tools.CeilingPOT(value);
  5808. break;
  5809. }
  5810. return Math.min(pot, max);
  5811. };
  5812. Tools.GetFilename = function (path) {
  5813. var index = path.lastIndexOf("/");
  5814. if (index < 0)
  5815. return path;
  5816. return path.substring(index + 1);
  5817. };
  5818. Tools.GetDOMTextContent = function (element) {
  5819. var result = "";
  5820. var child = element.firstChild;
  5821. while (child) {
  5822. if (child.nodeType === 3) {
  5823. result += child.textContent;
  5824. }
  5825. child = child.nextSibling;
  5826. }
  5827. return result;
  5828. };
  5829. Tools.ToDegrees = function (angle) {
  5830. return angle * 180 / Math.PI;
  5831. };
  5832. Tools.ToRadians = function (angle) {
  5833. return angle * Math.PI / 180;
  5834. };
  5835. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5836. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5837. var output = "";
  5838. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5839. var i = 0;
  5840. var bytes = new Uint8Array(buffer);
  5841. while (i < bytes.length) {
  5842. chr1 = bytes[i++];
  5843. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5844. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5845. enc1 = chr1 >> 2;
  5846. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5847. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5848. enc4 = chr3 & 63;
  5849. if (isNaN(chr2)) {
  5850. enc3 = enc4 = 64;
  5851. }
  5852. else if (isNaN(chr3)) {
  5853. enc4 = 64;
  5854. }
  5855. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5856. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5857. }
  5858. return "data:image/png;base64," + output;
  5859. };
  5860. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5861. if (bias === void 0) { bias = null; }
  5862. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5863. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5864. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5865. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5866. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5867. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5868. }
  5869. if (bias) {
  5870. minimum.x -= minimum.x * bias.x + bias.y;
  5871. minimum.y -= minimum.y * bias.x + bias.y;
  5872. minimum.z -= minimum.z * bias.x + bias.y;
  5873. maximum.x += maximum.x * bias.x + bias.y;
  5874. maximum.y += maximum.y * bias.x + bias.y;
  5875. maximum.z += maximum.z * bias.x + bias.y;
  5876. }
  5877. return {
  5878. minimum: minimum,
  5879. maximum: maximum
  5880. };
  5881. };
  5882. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5883. if (bias === void 0) { bias = null; }
  5884. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5885. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5886. if (!stride) {
  5887. stride = 3;
  5888. }
  5889. for (var index = start; index < start + count; index++) {
  5890. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5891. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5892. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5893. }
  5894. if (bias) {
  5895. minimum.x -= minimum.x * bias.x + bias.y;
  5896. minimum.y -= minimum.y * bias.x + bias.y;
  5897. minimum.z -= minimum.z * bias.x + bias.y;
  5898. maximum.x += maximum.x * bias.x + bias.y;
  5899. maximum.y += maximum.y * bias.x + bias.y;
  5900. maximum.z += maximum.z * bias.x + bias.y;
  5901. }
  5902. return {
  5903. minimum: minimum,
  5904. maximum: maximum
  5905. };
  5906. };
  5907. Tools.Vector2ArrayFeeder = function (array) {
  5908. return function (index) {
  5909. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5910. var length = isFloatArray ? array.length / 2 : array.length;
  5911. if (index >= length) {
  5912. return null;
  5913. }
  5914. if (isFloatArray) {
  5915. var fa = array;
  5916. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5917. }
  5918. var a = array;
  5919. return a[index];
  5920. };
  5921. };
  5922. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5923. if (bias === void 0) { bias = null; }
  5924. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5925. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5926. var i = 0;
  5927. var cur = feeder(i++);
  5928. while (cur) {
  5929. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5930. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5931. cur = feeder(i++);
  5932. }
  5933. if (bias) {
  5934. minimum.x -= minimum.x * bias.x + bias.y;
  5935. minimum.y -= minimum.y * bias.x + bias.y;
  5936. maximum.x += maximum.x * bias.x + bias.y;
  5937. maximum.y += maximum.y * bias.x + bias.y;
  5938. }
  5939. return {
  5940. minimum: minimum,
  5941. maximum: maximum
  5942. };
  5943. };
  5944. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5945. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5946. return null;
  5947. return Array.isArray(obj) ? obj : [obj];
  5948. };
  5949. // Misc.
  5950. Tools.GetPointerPrefix = function () {
  5951. var eventPrefix = "pointer";
  5952. // Check if pointer events are supported
  5953. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5954. eventPrefix = "mouse";
  5955. }
  5956. return eventPrefix;
  5957. };
  5958. /**
  5959. * @param func - the function to be called
  5960. * @param requester - the object that will request the next frame. Falls back to window.
  5961. */
  5962. Tools.QueueNewFrame = function (func, requester) {
  5963. if (!Tools.IsWindowObjectExist()) {
  5964. return setTimeout(func, 16);
  5965. }
  5966. if (!requester) {
  5967. requester = window;
  5968. }
  5969. if (requester.requestAnimationFrame) {
  5970. return requester.requestAnimationFrame(func);
  5971. }
  5972. else if (requester.msRequestAnimationFrame) {
  5973. return requester.msRequestAnimationFrame(func);
  5974. }
  5975. else if (requester.webkitRequestAnimationFrame) {
  5976. return requester.webkitRequestAnimationFrame(func);
  5977. }
  5978. else if (requester.mozRequestAnimationFrame) {
  5979. return requester.mozRequestAnimationFrame(func);
  5980. }
  5981. else if (requester.oRequestAnimationFrame) {
  5982. return requester.oRequestAnimationFrame(func);
  5983. }
  5984. else {
  5985. return window.setTimeout(func, 16);
  5986. }
  5987. };
  5988. Tools.RequestFullscreen = function (element) {
  5989. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5990. if (!requestFunction)
  5991. return;
  5992. requestFunction.call(element);
  5993. };
  5994. Tools.ExitFullscreen = function () {
  5995. if (document.exitFullscreen) {
  5996. document.exitFullscreen();
  5997. }
  5998. else if (document.mozCancelFullScreen) {
  5999. document.mozCancelFullScreen();
  6000. }
  6001. else if (document.webkitCancelFullScreen) {
  6002. document.webkitCancelFullScreen();
  6003. }
  6004. else if (document.msCancelFullScreen) {
  6005. document.msCancelFullScreen();
  6006. }
  6007. };
  6008. Tools.SetCorsBehavior = function (url, img) {
  6009. if (Tools.CorsBehavior) {
  6010. switch (typeof (Tools.CorsBehavior)) {
  6011. case "function":
  6012. var result = Tools.CorsBehavior(url);
  6013. if (result) {
  6014. img.crossOrigin = result;
  6015. }
  6016. break;
  6017. case "string":
  6018. default:
  6019. img.crossOrigin = Tools.CorsBehavior;
  6020. break;
  6021. }
  6022. }
  6023. };
  6024. // External files
  6025. Tools.CleanUrl = function (url) {
  6026. url = url.replace(/#/mg, "%23");
  6027. return url;
  6028. };
  6029. Tools.LoadImage = function (url, onLoad, onError, database) {
  6030. if (url instanceof ArrayBuffer) {
  6031. url = Tools.EncodeArrayBufferTobase64(url);
  6032. }
  6033. url = Tools.CleanUrl(url);
  6034. url = Tools.PreprocessUrl(url);
  6035. var img = new Image();
  6036. if (url.substr(0, 5) !== "data:") {
  6037. Tools.SetCorsBehavior(url, img);
  6038. }
  6039. img.onload = function () {
  6040. onLoad(img);
  6041. };
  6042. img.onerror = function (err) {
  6043. Tools.Error("Error while trying to load image: " + url);
  6044. if (Tools.UseFallbackTexture) {
  6045. img.src = Tools.fallbackTexture;
  6046. onLoad(img);
  6047. }
  6048. else {
  6049. onError("Error while trying to load image: " + url, err);
  6050. }
  6051. };
  6052. var noIndexedDB = function () {
  6053. img.src = url;
  6054. };
  6055. var loadFromIndexedDB = function () {
  6056. if (database) {
  6057. database.loadImageFromDB(url, img);
  6058. }
  6059. };
  6060. //ANY database to do!
  6061. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6062. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6063. }
  6064. else {
  6065. if (url.indexOf("file:") !== 0) {
  6066. noIndexedDB();
  6067. }
  6068. else {
  6069. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6070. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6071. try {
  6072. var blobURL;
  6073. try {
  6074. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6075. }
  6076. catch (ex) {
  6077. // Chrome doesn't support oneTimeOnly parameter
  6078. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6079. }
  6080. img.src = blobURL;
  6081. }
  6082. catch (e) {
  6083. img.src = "";
  6084. }
  6085. }
  6086. else {
  6087. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6088. img.src = Tools.fallbackTexture;
  6089. }
  6090. }
  6091. }
  6092. return img;
  6093. };
  6094. //ANY
  6095. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6096. url = Tools.CleanUrl(url);
  6097. url = Tools.PreprocessUrl(url);
  6098. var request = null;
  6099. var noIndexedDB = function () {
  6100. request = new XMLHttpRequest();
  6101. var loadUrl = Tools.BaseUrl + url;
  6102. request.open('GET', loadUrl, true);
  6103. if (useArrayBuffer) {
  6104. request.responseType = "arraybuffer";
  6105. }
  6106. if (progressCallBack) {
  6107. request.onprogress = progressCallBack;
  6108. }
  6109. request.onreadystatechange = function () {
  6110. var req = request;
  6111. // In case of undefined state in some browsers.
  6112. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6113. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6114. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6115. callback(!useArrayBuffer ? req.responseText : req.response);
  6116. }
  6117. else {
  6118. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6119. if (onError) {
  6120. onError(req, e);
  6121. }
  6122. else {
  6123. throw e;
  6124. }
  6125. }
  6126. }
  6127. };
  6128. request.send(null);
  6129. };
  6130. var loadFromIndexedDB = function () {
  6131. if (database) {
  6132. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6133. }
  6134. };
  6135. if (url.indexOf("file:") !== -1) {
  6136. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6137. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6138. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6139. }
  6140. else {
  6141. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6142. if (onError) {
  6143. var e = new Error(errorMessage);
  6144. onError(undefined, e);
  6145. }
  6146. else {
  6147. Tools.Error(errorMessage);
  6148. }
  6149. }
  6150. }
  6151. else {
  6152. // Caching all files
  6153. if (database && database.enableSceneOffline) {
  6154. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6155. }
  6156. else {
  6157. noIndexedDB();
  6158. }
  6159. }
  6160. return request;
  6161. };
  6162. /**
  6163. * Load a script (identified by an url). When the url returns, the
  6164. * content of this file is added into a new script element, attached to the DOM (body element)
  6165. */
  6166. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6167. var head = document.getElementsByTagName('head')[0];
  6168. var script = document.createElement('script');
  6169. script.type = 'text/javascript';
  6170. script.src = scriptUrl;
  6171. script.onload = function () {
  6172. if (onSuccess) {
  6173. onSuccess();
  6174. }
  6175. };
  6176. script.onerror = function (e) {
  6177. if (onError) {
  6178. onError("Unable to load script", e);
  6179. }
  6180. };
  6181. head.appendChild(script);
  6182. };
  6183. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6184. var reader = new FileReader();
  6185. reader.onload = function (e) {
  6186. //target doesn't have result from ts 1.3
  6187. callback(e.target['result']);
  6188. };
  6189. reader.onprogress = progressCallback;
  6190. reader.readAsDataURL(fileToLoad);
  6191. };
  6192. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6193. var reader = new FileReader();
  6194. reader.onerror = function (e) {
  6195. Tools.Log("Error while reading file: " + fileToLoad.name);
  6196. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6197. };
  6198. reader.onload = function (e) {
  6199. //target doesn't have result from ts 1.3
  6200. callback(e.target['result']);
  6201. };
  6202. if (progressCallBack) {
  6203. reader.onprogress = progressCallBack;
  6204. }
  6205. if (!useArrayBuffer) {
  6206. // Asynchronous read
  6207. reader.readAsText(fileToLoad);
  6208. }
  6209. else {
  6210. reader.readAsArrayBuffer(fileToLoad);
  6211. }
  6212. };
  6213. //returns a downloadable url to a file content.
  6214. Tools.FileAsURL = function (content) {
  6215. var fileBlob = new Blob([content]);
  6216. var url = window.URL || window.webkitURL;
  6217. var link = url.createObjectURL(fileBlob);
  6218. return link;
  6219. };
  6220. // Misc.
  6221. Tools.Format = function (value, decimals) {
  6222. if (decimals === void 0) { decimals = 2; }
  6223. return value.toFixed(decimals);
  6224. };
  6225. Tools.CheckExtends = function (v, min, max) {
  6226. if (v.x < min.x)
  6227. min.x = v.x;
  6228. if (v.y < min.y)
  6229. min.y = v.y;
  6230. if (v.z < min.z)
  6231. min.z = v.z;
  6232. if (v.x > max.x)
  6233. max.x = v.x;
  6234. if (v.y > max.y)
  6235. max.y = v.y;
  6236. if (v.z > max.z)
  6237. max.z = v.z;
  6238. };
  6239. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6240. for (var prop in source) {
  6241. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6242. continue;
  6243. }
  6244. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6245. continue;
  6246. }
  6247. var sourceValue = source[prop];
  6248. var typeOfSourceValue = typeof sourceValue;
  6249. if (typeOfSourceValue === "function") {
  6250. continue;
  6251. }
  6252. if (typeOfSourceValue === "object") {
  6253. if (sourceValue instanceof Array) {
  6254. destination[prop] = [];
  6255. if (sourceValue.length > 0) {
  6256. if (typeof sourceValue[0] == "object") {
  6257. for (var index = 0; index < sourceValue.length; index++) {
  6258. var clonedValue = cloneValue(sourceValue[index], destination);
  6259. if (destination[prop].indexOf(clonedValue) === -1) {
  6260. destination[prop].push(clonedValue);
  6261. }
  6262. }
  6263. }
  6264. else {
  6265. destination[prop] = sourceValue.slice(0);
  6266. }
  6267. }
  6268. }
  6269. else {
  6270. destination[prop] = cloneValue(sourceValue, destination);
  6271. }
  6272. }
  6273. else {
  6274. destination[prop] = sourceValue;
  6275. }
  6276. }
  6277. };
  6278. Tools.IsEmpty = function (obj) {
  6279. for (var i in obj) {
  6280. if (obj.hasOwnProperty(i)) {
  6281. return false;
  6282. }
  6283. }
  6284. return true;
  6285. };
  6286. Tools.RegisterTopRootEvents = function (events) {
  6287. for (var index = 0; index < events.length; index++) {
  6288. var event = events[index];
  6289. window.addEventListener(event.name, event.handler, false);
  6290. try {
  6291. if (window.parent) {
  6292. window.parent.addEventListener(event.name, event.handler, false);
  6293. }
  6294. }
  6295. catch (e) {
  6296. // Silently fails...
  6297. }
  6298. }
  6299. };
  6300. Tools.UnregisterTopRootEvents = function (events) {
  6301. for (var index = 0; index < events.length; index++) {
  6302. var event = events[index];
  6303. window.removeEventListener(event.name, event.handler);
  6304. try {
  6305. if (window.parent) {
  6306. window.parent.removeEventListener(event.name, event.handler);
  6307. }
  6308. }
  6309. catch (e) {
  6310. // Silently fails...
  6311. }
  6312. }
  6313. };
  6314. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6315. if (mimeType === void 0) { mimeType = "image/png"; }
  6316. // Read the contents of the framebuffer
  6317. var numberOfChannelsByLine = width * 4;
  6318. var halfHeight = height / 2;
  6319. //Reading datas from WebGL
  6320. var data = engine.readPixels(0, 0, width, height);
  6321. //To flip image on Y axis.
  6322. for (var i = 0; i < halfHeight; i++) {
  6323. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6324. var currentCell = j + i * numberOfChannelsByLine;
  6325. var targetLine = height - i - 1;
  6326. var targetCell = j + targetLine * numberOfChannelsByLine;
  6327. var temp = data[currentCell];
  6328. data[currentCell] = data[targetCell];
  6329. data[targetCell] = temp;
  6330. }
  6331. }
  6332. // Create a 2D canvas to store the result
  6333. if (!screenshotCanvas) {
  6334. screenshotCanvas = document.createElement('canvas');
  6335. }
  6336. screenshotCanvas.width = width;
  6337. screenshotCanvas.height = height;
  6338. var context = screenshotCanvas.getContext('2d');
  6339. if (context) {
  6340. // Copy the pixels to a 2D canvas
  6341. var imageData = context.createImageData(width, height);
  6342. var castData = (imageData.data);
  6343. castData.set(data);
  6344. context.putImageData(imageData, 0, 0);
  6345. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6346. }
  6347. };
  6348. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6349. if (mimeType === void 0) { mimeType = "image/png"; }
  6350. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6351. if (successCallback) {
  6352. successCallback(base64Image);
  6353. }
  6354. else {
  6355. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6356. if (("download" in document.createElement("a"))) {
  6357. var a = window.document.createElement("a");
  6358. a.href = base64Image;
  6359. var date = new Date();
  6360. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6361. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6362. window.document.body.appendChild(a);
  6363. a.addEventListener("click", function () {
  6364. if (a.parentElement) {
  6365. a.parentElement.removeChild(a);
  6366. }
  6367. });
  6368. a.click();
  6369. //Or opening a new tab with the image if it is not possible to automatically start download.
  6370. }
  6371. else {
  6372. var newWindow = window.open("");
  6373. var img = newWindow.document.createElement("img");
  6374. img.src = base64Image;
  6375. newWindow.document.body.appendChild(img);
  6376. }
  6377. }
  6378. };
  6379. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6380. if (mimeType === void 0) { mimeType = "image/png"; }
  6381. var width;
  6382. var height;
  6383. // If a precision value is specified
  6384. if (size.precision) {
  6385. width = Math.round(engine.getRenderWidth() * size.precision);
  6386. height = Math.round(width / engine.getAspectRatio(camera));
  6387. }
  6388. else if (size.width && size.height) {
  6389. width = size.width;
  6390. height = size.height;
  6391. }
  6392. else if (size.width && !size.height) {
  6393. width = size.width;
  6394. height = Math.round(width / engine.getAspectRatio(camera));
  6395. }
  6396. else if (size.height && !size.width) {
  6397. height = size.height;
  6398. width = Math.round(height * engine.getAspectRatio(camera));
  6399. }
  6400. else if (!isNaN(size)) {
  6401. height = size;
  6402. width = size;
  6403. }
  6404. else {
  6405. Tools.Error("Invalid 'size' parameter !");
  6406. return;
  6407. }
  6408. if (!screenshotCanvas) {
  6409. screenshotCanvas = document.createElement('canvas');
  6410. }
  6411. screenshotCanvas.width = width;
  6412. screenshotCanvas.height = height;
  6413. var renderContext = screenshotCanvas.getContext("2d");
  6414. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6415. var newWidth = width;
  6416. var newHeight = newWidth / ratio;
  6417. if (newHeight > height) {
  6418. newHeight = height;
  6419. newWidth = newHeight * ratio;
  6420. }
  6421. var offsetX = Math.max(0, width - newWidth) / 2;
  6422. var offsetY = Math.max(0, height - newHeight) / 2;
  6423. var renderingCanvas = engine.getRenderingCanvas();
  6424. if (renderContext && renderingCanvas) {
  6425. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6426. }
  6427. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6428. };
  6429. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6430. if (mimeType === void 0) { mimeType = "image/png"; }
  6431. if (samples === void 0) { samples = 1; }
  6432. var width;
  6433. var height;
  6434. //If a precision value is specified
  6435. if (size.precision) {
  6436. width = Math.round(engine.getRenderWidth() * size.precision);
  6437. height = Math.round(width / engine.getAspectRatio(camera));
  6438. size = { width: width, height: height };
  6439. }
  6440. else if (size.width && size.height) {
  6441. width = size.width;
  6442. height = size.height;
  6443. }
  6444. else if (size.width && !size.height) {
  6445. width = size.width;
  6446. height = Math.round(width / engine.getAspectRatio(camera));
  6447. size = { width: width, height: height };
  6448. }
  6449. else if (size.height && !size.width) {
  6450. height = size.height;
  6451. width = Math.round(height * engine.getAspectRatio(camera));
  6452. size = { width: width, height: height };
  6453. }
  6454. else if (!isNaN(size)) {
  6455. height = size;
  6456. width = size;
  6457. }
  6458. else {
  6459. Tools.Error("Invalid 'size' parameter !");
  6460. return;
  6461. }
  6462. var scene = camera.getScene();
  6463. var previousCamera = null;
  6464. if (scene.activeCamera !== camera) {
  6465. previousCamera = scene.activeCamera;
  6466. scene.activeCamera = camera;
  6467. }
  6468. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6469. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6470. texture.renderList = null;
  6471. texture.samples = samples;
  6472. texture.onAfterRenderObservable.add(function () {
  6473. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6474. });
  6475. scene.incrementRenderId();
  6476. scene.resetCachedMaterial();
  6477. texture.render(true);
  6478. texture.dispose();
  6479. if (previousCamera) {
  6480. scene.activeCamera = previousCamera;
  6481. }
  6482. camera.getProjectionMatrix(true); // Force cache refresh;
  6483. };
  6484. // XHR response validator for local file scenario
  6485. Tools.ValidateXHRData = function (xhr, dataType) {
  6486. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6487. if (dataType === void 0) { dataType = 7; }
  6488. try {
  6489. if (dataType & 1) {
  6490. if (xhr.responseText && xhr.responseText.length > 0) {
  6491. return true;
  6492. }
  6493. else if (dataType === 1) {
  6494. return false;
  6495. }
  6496. }
  6497. if (dataType & 2) {
  6498. // Check header width and height since there is no "TGA" magic number
  6499. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6500. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6501. return true;
  6502. }
  6503. else if (dataType === 2) {
  6504. return false;
  6505. }
  6506. }
  6507. if (dataType & 4) {
  6508. // Check for the "DDS" magic number
  6509. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6510. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6511. return true;
  6512. }
  6513. else {
  6514. return false;
  6515. }
  6516. }
  6517. }
  6518. catch (e) {
  6519. // Global protection
  6520. }
  6521. return false;
  6522. };
  6523. /**
  6524. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6525. * Be aware Math.random() could cause collisions, but:
  6526. * "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"
  6527. */
  6528. Tools.RandomId = function () {
  6529. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6530. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6531. return v.toString(16);
  6532. });
  6533. };
  6534. Object.defineProperty(Tools, "NoneLogLevel", {
  6535. get: function () {
  6536. return Tools._NoneLogLevel;
  6537. },
  6538. enumerable: true,
  6539. configurable: true
  6540. });
  6541. Object.defineProperty(Tools, "MessageLogLevel", {
  6542. get: function () {
  6543. return Tools._MessageLogLevel;
  6544. },
  6545. enumerable: true,
  6546. configurable: true
  6547. });
  6548. Object.defineProperty(Tools, "WarningLogLevel", {
  6549. get: function () {
  6550. return Tools._WarningLogLevel;
  6551. },
  6552. enumerable: true,
  6553. configurable: true
  6554. });
  6555. Object.defineProperty(Tools, "ErrorLogLevel", {
  6556. get: function () {
  6557. return Tools._ErrorLogLevel;
  6558. },
  6559. enumerable: true,
  6560. configurable: true
  6561. });
  6562. Object.defineProperty(Tools, "AllLogLevel", {
  6563. get: function () {
  6564. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6565. },
  6566. enumerable: true,
  6567. configurable: true
  6568. });
  6569. Tools._AddLogEntry = function (entry) {
  6570. Tools._LogCache = entry + Tools._LogCache;
  6571. if (Tools.OnNewCacheEntry) {
  6572. Tools.OnNewCacheEntry(entry);
  6573. }
  6574. };
  6575. Tools._FormatMessage = function (message) {
  6576. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6577. var date = new Date();
  6578. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6579. };
  6580. Tools._LogDisabled = function (message) {
  6581. // nothing to do
  6582. };
  6583. Tools._LogEnabled = function (message) {
  6584. var formattedMessage = Tools._FormatMessage(message);
  6585. console.log("BJS - " + formattedMessage);
  6586. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6587. Tools._AddLogEntry(entry);
  6588. };
  6589. Tools._WarnDisabled = function (message) {
  6590. // nothing to do
  6591. };
  6592. Tools._WarnEnabled = function (message) {
  6593. var formattedMessage = Tools._FormatMessage(message);
  6594. console.warn("BJS - " + formattedMessage);
  6595. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6596. Tools._AddLogEntry(entry);
  6597. };
  6598. Tools._ErrorDisabled = function (message) {
  6599. // nothing to do
  6600. };
  6601. Tools._ErrorEnabled = function (message) {
  6602. Tools.errorsCount++;
  6603. var formattedMessage = Tools._FormatMessage(message);
  6604. console.error("BJS - " + formattedMessage);
  6605. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6606. Tools._AddLogEntry(entry);
  6607. };
  6608. Object.defineProperty(Tools, "LogCache", {
  6609. get: function () {
  6610. return Tools._LogCache;
  6611. },
  6612. enumerable: true,
  6613. configurable: true
  6614. });
  6615. Tools.ClearLogCache = function () {
  6616. Tools._LogCache = "";
  6617. Tools.errorsCount = 0;
  6618. };
  6619. Object.defineProperty(Tools, "LogLevels", {
  6620. set: function (level) {
  6621. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6622. Tools.Log = Tools._LogEnabled;
  6623. }
  6624. else {
  6625. Tools.Log = Tools._LogDisabled;
  6626. }
  6627. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6628. Tools.Warn = Tools._WarnEnabled;
  6629. }
  6630. else {
  6631. Tools.Warn = Tools._WarnDisabled;
  6632. }
  6633. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6634. Tools.Error = Tools._ErrorEnabled;
  6635. }
  6636. else {
  6637. Tools.Error = Tools._ErrorDisabled;
  6638. }
  6639. },
  6640. enumerable: true,
  6641. configurable: true
  6642. });
  6643. Tools.IsWindowObjectExist = function () {
  6644. return (typeof window) !== "undefined";
  6645. };
  6646. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6647. get: function () {
  6648. return Tools._PerformanceNoneLogLevel;
  6649. },
  6650. enumerable: true,
  6651. configurable: true
  6652. });
  6653. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6654. get: function () {
  6655. return Tools._PerformanceUserMarkLogLevel;
  6656. },
  6657. enumerable: true,
  6658. configurable: true
  6659. });
  6660. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6661. get: function () {
  6662. return Tools._PerformanceConsoleLogLevel;
  6663. },
  6664. enumerable: true,
  6665. configurable: true
  6666. });
  6667. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6668. set: function (level) {
  6669. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6670. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6671. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6672. return;
  6673. }
  6674. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6675. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6676. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6677. return;
  6678. }
  6679. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6680. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6681. },
  6682. enumerable: true,
  6683. configurable: true
  6684. });
  6685. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6686. };
  6687. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6688. };
  6689. Tools._StartUserMark = function (counterName, condition) {
  6690. if (condition === void 0) { condition = true; }
  6691. if (!Tools._performance) {
  6692. if (!Tools.IsWindowObjectExist()) {
  6693. return;
  6694. }
  6695. Tools._performance = window.performance;
  6696. }
  6697. if (!condition || !Tools._performance.mark) {
  6698. return;
  6699. }
  6700. Tools._performance.mark(counterName + "-Begin");
  6701. };
  6702. Tools._EndUserMark = function (counterName, condition) {
  6703. if (condition === void 0) { condition = true; }
  6704. if (!condition || !Tools._performance.mark) {
  6705. return;
  6706. }
  6707. Tools._performance.mark(counterName + "-End");
  6708. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6709. };
  6710. Tools._StartPerformanceConsole = function (counterName, condition) {
  6711. if (condition === void 0) { condition = true; }
  6712. if (!condition) {
  6713. return;
  6714. }
  6715. Tools._StartUserMark(counterName, condition);
  6716. if (console.time) {
  6717. console.time(counterName);
  6718. }
  6719. };
  6720. Tools._EndPerformanceConsole = function (counterName, condition) {
  6721. if (condition === void 0) { condition = true; }
  6722. if (!condition) {
  6723. return;
  6724. }
  6725. Tools._EndUserMark(counterName, condition);
  6726. if (console.time) {
  6727. console.timeEnd(counterName);
  6728. }
  6729. };
  6730. Object.defineProperty(Tools, "Now", {
  6731. get: function () {
  6732. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6733. return window.performance.now();
  6734. }
  6735. return new Date().getTime();
  6736. },
  6737. enumerable: true,
  6738. configurable: true
  6739. });
  6740. /**
  6741. * This method will return the name of the class used to create the instance of the given object.
  6742. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6743. * @param object the object to get the class name from
  6744. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6745. */
  6746. Tools.GetClassName = function (object, isType) {
  6747. if (isType === void 0) { isType = false; }
  6748. var name = null;
  6749. if (!isType && object.getClassName) {
  6750. name = object.getClassName();
  6751. }
  6752. else {
  6753. if (object instanceof Object) {
  6754. var classObj = isType ? object : Object.getPrototypeOf(object);
  6755. name = classObj.constructor["__bjsclassName__"];
  6756. }
  6757. if (!name) {
  6758. name = typeof object;
  6759. }
  6760. }
  6761. return name;
  6762. };
  6763. Tools.First = function (array, predicate) {
  6764. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6765. var el = array_1[_i];
  6766. if (predicate(el)) {
  6767. return el;
  6768. }
  6769. }
  6770. return null;
  6771. };
  6772. /**
  6773. * This method will return the name of the full name of the class, including its owning module (if any).
  6774. * 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).
  6775. * @param object the object to get the class name from
  6776. * @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.
  6777. */
  6778. Tools.getFullClassName = function (object, isType) {
  6779. if (isType === void 0) { isType = false; }
  6780. var className = null;
  6781. var moduleName = null;
  6782. if (!isType && object.getClassName) {
  6783. className = object.getClassName();
  6784. }
  6785. else {
  6786. if (object instanceof Object) {
  6787. var classObj = isType ? object : Object.getPrototypeOf(object);
  6788. className = classObj.constructor["__bjsclassName__"];
  6789. moduleName = classObj.constructor["__bjsmoduleName__"];
  6790. }
  6791. if (!className) {
  6792. className = typeof object;
  6793. }
  6794. }
  6795. if (!className) {
  6796. return null;
  6797. }
  6798. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6799. };
  6800. /**
  6801. * 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.
  6802. * @param array
  6803. */
  6804. Tools.arrayOrStringFeeder = function (array) {
  6805. return function (index) {
  6806. if (index >= array.length) {
  6807. return null;
  6808. }
  6809. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6810. if (val && val.getHashCode) {
  6811. val = val.getHashCode();
  6812. }
  6813. if (typeof val === "string") {
  6814. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6815. }
  6816. return val;
  6817. };
  6818. };
  6819. /**
  6820. * Compute the hashCode of a stream of number
  6821. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6822. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6823. * @return the hash code computed
  6824. */
  6825. Tools.hashCodeFromStream = function (feeder) {
  6826. // Based from here: http://stackoverflow.com/a/7616484/802124
  6827. var hash = 0;
  6828. var index = 0;
  6829. var chr = feeder(index++);
  6830. while (chr != null) {
  6831. hash = ((hash << 5) - hash) + chr;
  6832. hash |= 0; // Convert to 32bit integer
  6833. chr = feeder(index++);
  6834. }
  6835. return hash;
  6836. };
  6837. Tools.BaseUrl = "";
  6838. Tools.CorsBehavior = "anonymous";
  6839. Tools.UseFallbackTexture = true;
  6840. /**
  6841. * Use this object to register external classes like custom textures or material
  6842. * to allow the laoders to instantiate them
  6843. */
  6844. Tools.RegisteredExternalClasses = {};
  6845. // Used in case of a texture loading problem
  6846. 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";
  6847. Tools.PreprocessUrl = function (url) {
  6848. return url;
  6849. };
  6850. // Logs
  6851. Tools._NoneLogLevel = 0;
  6852. Tools._MessageLogLevel = 1;
  6853. Tools._WarningLogLevel = 2;
  6854. Tools._ErrorLogLevel = 4;
  6855. Tools._LogCache = "";
  6856. Tools.errorsCount = 0;
  6857. Tools.Log = Tools._LogEnabled;
  6858. Tools.Warn = Tools._WarnEnabled;
  6859. Tools.Error = Tools._ErrorEnabled;
  6860. // Performances
  6861. Tools._PerformanceNoneLogLevel = 0;
  6862. Tools._PerformanceUserMarkLogLevel = 1;
  6863. Tools._PerformanceConsoleLogLevel = 2;
  6864. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6865. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6866. return Tools;
  6867. }());
  6868. BABYLON.Tools = Tools;
  6869. /**
  6870. * This class is used to track a performance counter which is number based.
  6871. * The user has access to many properties which give statistics of different nature
  6872. *
  6873. * The implementer can track two kinds of Performance Counter: time and count
  6874. * 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.
  6875. * 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.
  6876. */
  6877. var PerfCounter = /** @class */ (function () {
  6878. function PerfCounter() {
  6879. this._startMonitoringTime = 0;
  6880. this._min = 0;
  6881. this._max = 0;
  6882. this._average = 0;
  6883. this._lastSecAverage = 0;
  6884. this._current = 0;
  6885. this._totalValueCount = 0;
  6886. this._totalAccumulated = 0;
  6887. this._lastSecAccumulated = 0;
  6888. this._lastSecTime = 0;
  6889. this._lastSecValueCount = 0;
  6890. }
  6891. Object.defineProperty(PerfCounter.prototype, "min", {
  6892. /**
  6893. * Returns the smallest value ever
  6894. */
  6895. get: function () {
  6896. return this._min;
  6897. },
  6898. enumerable: true,
  6899. configurable: true
  6900. });
  6901. Object.defineProperty(PerfCounter.prototype, "max", {
  6902. /**
  6903. * Returns the biggest value ever
  6904. */
  6905. get: function () {
  6906. return this._max;
  6907. },
  6908. enumerable: true,
  6909. configurable: true
  6910. });
  6911. Object.defineProperty(PerfCounter.prototype, "average", {
  6912. /**
  6913. * Returns the average value since the performance counter is running
  6914. */
  6915. get: function () {
  6916. return this._average;
  6917. },
  6918. enumerable: true,
  6919. configurable: true
  6920. });
  6921. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6922. /**
  6923. * Returns the average value of the last second the counter was monitored
  6924. */
  6925. get: function () {
  6926. return this._lastSecAverage;
  6927. },
  6928. enumerable: true,
  6929. configurable: true
  6930. });
  6931. Object.defineProperty(PerfCounter.prototype, "current", {
  6932. /**
  6933. * Returns the current value
  6934. */
  6935. get: function () {
  6936. return this._current;
  6937. },
  6938. enumerable: true,
  6939. configurable: true
  6940. });
  6941. Object.defineProperty(PerfCounter.prototype, "total", {
  6942. get: function () {
  6943. return this._totalAccumulated;
  6944. },
  6945. enumerable: true,
  6946. configurable: true
  6947. });
  6948. Object.defineProperty(PerfCounter.prototype, "count", {
  6949. get: function () {
  6950. return this._totalValueCount;
  6951. },
  6952. enumerable: true,
  6953. configurable: true
  6954. });
  6955. /**
  6956. * Call this method to start monitoring a new frame.
  6957. * 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.
  6958. */
  6959. PerfCounter.prototype.fetchNewFrame = function () {
  6960. this._totalValueCount++;
  6961. this._current = 0;
  6962. this._lastSecValueCount++;
  6963. };
  6964. /**
  6965. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6966. * @param newCount the count value to add to the monitored count
  6967. * @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.
  6968. */
  6969. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6970. if (!PerfCounter.Enabled) {
  6971. return;
  6972. }
  6973. this._current += newCount;
  6974. if (fetchResult) {
  6975. this._fetchResult();
  6976. }
  6977. };
  6978. /**
  6979. * Start monitoring this performance counter
  6980. */
  6981. PerfCounter.prototype.beginMonitoring = function () {
  6982. if (!PerfCounter.Enabled) {
  6983. return;
  6984. }
  6985. this._startMonitoringTime = Tools.Now;
  6986. };
  6987. /**
  6988. * Compute the time lapsed since the previous beginMonitoring() call.
  6989. * @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
  6990. */
  6991. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6992. if (newFrame === void 0) { newFrame = true; }
  6993. if (!PerfCounter.Enabled) {
  6994. return;
  6995. }
  6996. if (newFrame) {
  6997. this.fetchNewFrame();
  6998. }
  6999. var currentTime = Tools.Now;
  7000. this._current = currentTime - this._startMonitoringTime;
  7001. if (newFrame) {
  7002. this._fetchResult();
  7003. }
  7004. };
  7005. PerfCounter.prototype._fetchResult = function () {
  7006. this._totalAccumulated += this._current;
  7007. this._lastSecAccumulated += this._current;
  7008. // Min/Max update
  7009. this._min = Math.min(this._min, this._current);
  7010. this._max = Math.max(this._max, this._current);
  7011. this._average = this._totalAccumulated / this._totalValueCount;
  7012. // Reset last sec?
  7013. var now = Tools.Now;
  7014. if ((now - this._lastSecTime) > 1000) {
  7015. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7016. this._lastSecTime = now;
  7017. this._lastSecAccumulated = 0;
  7018. this._lastSecValueCount = 0;
  7019. }
  7020. };
  7021. PerfCounter.Enabled = true;
  7022. return PerfCounter;
  7023. }());
  7024. BABYLON.PerfCounter = PerfCounter;
  7025. /**
  7026. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7027. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7028. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7029. * @param name The name of the class, case should be preserved
  7030. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7031. */
  7032. function className(name, module) {
  7033. return function (target) {
  7034. target["__bjsclassName__"] = name;
  7035. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7036. };
  7037. }
  7038. BABYLON.className = className;
  7039. /**
  7040. * An implementation of a loop for asynchronous functions.
  7041. */
  7042. var AsyncLoop = /** @class */ (function () {
  7043. /**
  7044. * Constroctor.
  7045. * @param iterations the number of iterations.
  7046. * @param _fn the function to run each iteration
  7047. * @param _successCallback the callback that will be called upon succesful execution
  7048. * @param offset starting offset.
  7049. */
  7050. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7051. if (offset === void 0) { offset = 0; }
  7052. this.iterations = iterations;
  7053. this._fn = _fn;
  7054. this._successCallback = _successCallback;
  7055. this.index = offset - 1;
  7056. this._done = false;
  7057. }
  7058. /**
  7059. * Execute the next iteration. Must be called after the last iteration was finished.
  7060. */
  7061. AsyncLoop.prototype.executeNext = function () {
  7062. if (!this._done) {
  7063. if (this.index + 1 < this.iterations) {
  7064. ++this.index;
  7065. this._fn(this);
  7066. }
  7067. else {
  7068. this.breakLoop();
  7069. }
  7070. }
  7071. };
  7072. /**
  7073. * Break the loop and run the success callback.
  7074. */
  7075. AsyncLoop.prototype.breakLoop = function () {
  7076. this._done = true;
  7077. this._successCallback();
  7078. };
  7079. /**
  7080. * Helper function
  7081. */
  7082. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7083. if (offset === void 0) { offset = 0; }
  7084. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7085. loop.executeNext();
  7086. return loop;
  7087. };
  7088. /**
  7089. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7090. * @param iterations total number of iterations
  7091. * @param syncedIterations number of synchronous iterations in each async iteration.
  7092. * @param fn the function to call each iteration.
  7093. * @param callback a success call back that will be called when iterating stops.
  7094. * @param breakFunction a break condition (optional)
  7095. * @param timeout timeout settings for the setTimeout function. default - 0.
  7096. * @constructor
  7097. */
  7098. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7099. if (timeout === void 0) { timeout = 0; }
  7100. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7101. if (breakFunction && breakFunction())
  7102. loop.breakLoop();
  7103. else {
  7104. setTimeout(function () {
  7105. for (var i = 0; i < syncedIterations; ++i) {
  7106. var iteration = (loop.index * syncedIterations) + i;
  7107. if (iteration >= iterations)
  7108. break;
  7109. fn(iteration);
  7110. if (breakFunction && breakFunction()) {
  7111. loop.breakLoop();
  7112. break;
  7113. }
  7114. }
  7115. loop.executeNext();
  7116. }, timeout);
  7117. }
  7118. }, callback);
  7119. };
  7120. return AsyncLoop;
  7121. }());
  7122. BABYLON.AsyncLoop = AsyncLoop;
  7123. })(BABYLON || (BABYLON = {}));
  7124. //# sourceMappingURL=babylon.tools.js.map
  7125. var BABYLON;
  7126. (function (BABYLON) {
  7127. var Internals;
  7128. (function (Internals) {
  7129. var _AlphaState = /** @class */ (function () {
  7130. /**
  7131. * Initializes the state.
  7132. */
  7133. function _AlphaState() {
  7134. this._isAlphaBlendDirty = false;
  7135. this._isBlendFunctionParametersDirty = false;
  7136. this._isBlendEquationParametersDirty = false;
  7137. this._isBlendConstantsDirty = false;
  7138. this._alphaBlend = false;
  7139. this._blendFunctionParameters = new Array(4);
  7140. this._blendEquationParameters = new Array(2);
  7141. this._blendConstants = new Array(4);
  7142. this.reset();
  7143. }
  7144. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7145. get: function () {
  7146. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7147. },
  7148. enumerable: true,
  7149. configurable: true
  7150. });
  7151. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7152. get: function () {
  7153. return this._alphaBlend;
  7154. },
  7155. set: function (value) {
  7156. if (this._alphaBlend === value) {
  7157. return;
  7158. }
  7159. this._alphaBlend = value;
  7160. this._isAlphaBlendDirty = true;
  7161. },
  7162. enumerable: true,
  7163. configurable: true
  7164. });
  7165. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7166. if (this._blendConstants[0] === r &&
  7167. this._blendConstants[1] === g &&
  7168. this._blendConstants[2] === b &&
  7169. this._blendConstants[3] === a) {
  7170. return;
  7171. }
  7172. this._blendConstants[0] = r;
  7173. this._blendConstants[1] = g;
  7174. this._blendConstants[2] = b;
  7175. this._blendConstants[3] = a;
  7176. this._isBlendConstantsDirty = true;
  7177. };
  7178. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7179. if (this._blendFunctionParameters[0] === value0 &&
  7180. this._blendFunctionParameters[1] === value1 &&
  7181. this._blendFunctionParameters[2] === value2 &&
  7182. this._blendFunctionParameters[3] === value3) {
  7183. return;
  7184. }
  7185. this._blendFunctionParameters[0] = value0;
  7186. this._blendFunctionParameters[1] = value1;
  7187. this._blendFunctionParameters[2] = value2;
  7188. this._blendFunctionParameters[3] = value3;
  7189. this._isBlendFunctionParametersDirty = true;
  7190. };
  7191. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7192. if (this._blendEquationParameters[0] === rgb &&
  7193. this._blendEquationParameters[1] === alpha) {
  7194. return;
  7195. }
  7196. this._blendEquationParameters[0] = rgb;
  7197. this._blendEquationParameters[1] = alpha;
  7198. this._isBlendEquationParametersDirty = true;
  7199. };
  7200. _AlphaState.prototype.reset = function () {
  7201. this._alphaBlend = false;
  7202. this._blendFunctionParameters[0] = null;
  7203. this._blendFunctionParameters[1] = null;
  7204. this._blendFunctionParameters[2] = null;
  7205. this._blendFunctionParameters[3] = null;
  7206. this._blendEquationParameters[0] = null;
  7207. this._blendEquationParameters[1] = null;
  7208. this._blendConstants[0] = null;
  7209. this._blendConstants[1] = null;
  7210. this._blendConstants[2] = null;
  7211. this._blendConstants[3] = null;
  7212. this._isAlphaBlendDirty = true;
  7213. this._isBlendFunctionParametersDirty = false;
  7214. this._isBlendEquationParametersDirty = false;
  7215. this._isBlendConstantsDirty = false;
  7216. };
  7217. _AlphaState.prototype.apply = function (gl) {
  7218. if (!this.isDirty) {
  7219. return;
  7220. }
  7221. // Alpha blend
  7222. if (this._isAlphaBlendDirty) {
  7223. if (this._alphaBlend) {
  7224. gl.enable(gl.BLEND);
  7225. }
  7226. else {
  7227. gl.disable(gl.BLEND);
  7228. }
  7229. this._isAlphaBlendDirty = false;
  7230. }
  7231. // Alpha function
  7232. if (this._isBlendFunctionParametersDirty) {
  7233. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7234. this._isBlendFunctionParametersDirty = false;
  7235. }
  7236. // Alpha equation
  7237. if (this._isBlendEquationParametersDirty) {
  7238. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7239. this._isBlendEquationParametersDirty = false;
  7240. }
  7241. // Constants
  7242. if (this._isBlendConstantsDirty) {
  7243. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7244. this._isBlendConstantsDirty = false;
  7245. }
  7246. };
  7247. return _AlphaState;
  7248. }());
  7249. Internals._AlphaState = _AlphaState;
  7250. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7251. })(BABYLON || (BABYLON = {}));
  7252. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7253. var BABYLON;
  7254. (function (BABYLON) {
  7255. var Internals;
  7256. (function (Internals) {
  7257. var _DepthCullingState = /** @class */ (function () {
  7258. /**
  7259. * Initializes the state.
  7260. */
  7261. function _DepthCullingState() {
  7262. this._isDepthTestDirty = false;
  7263. this._isDepthMaskDirty = false;
  7264. this._isDepthFuncDirty = false;
  7265. this._isCullFaceDirty = false;
  7266. this._isCullDirty = false;
  7267. this._isZOffsetDirty = false;
  7268. this.reset();
  7269. }
  7270. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7271. get: function () {
  7272. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7273. },
  7274. enumerable: true,
  7275. configurable: true
  7276. });
  7277. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7278. get: function () {
  7279. return this._zOffset;
  7280. },
  7281. set: function (value) {
  7282. if (this._zOffset === value) {
  7283. return;
  7284. }
  7285. this._zOffset = value;
  7286. this._isZOffsetDirty = true;
  7287. },
  7288. enumerable: true,
  7289. configurable: true
  7290. });
  7291. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7292. get: function () {
  7293. return this._cullFace;
  7294. },
  7295. set: function (value) {
  7296. if (this._cullFace === value) {
  7297. return;
  7298. }
  7299. this._cullFace = value;
  7300. this._isCullFaceDirty = true;
  7301. },
  7302. enumerable: true,
  7303. configurable: true
  7304. });
  7305. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7306. get: function () {
  7307. return this._cull;
  7308. },
  7309. set: function (value) {
  7310. if (this._cull === value) {
  7311. return;
  7312. }
  7313. this._cull = value;
  7314. this._isCullDirty = true;
  7315. },
  7316. enumerable: true,
  7317. configurable: true
  7318. });
  7319. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7320. get: function () {
  7321. return this._depthFunc;
  7322. },
  7323. set: function (value) {
  7324. if (this._depthFunc === value) {
  7325. return;
  7326. }
  7327. this._depthFunc = value;
  7328. this._isDepthFuncDirty = true;
  7329. },
  7330. enumerable: true,
  7331. configurable: true
  7332. });
  7333. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7334. get: function () {
  7335. return this._depthMask;
  7336. },
  7337. set: function (value) {
  7338. if (this._depthMask === value) {
  7339. return;
  7340. }
  7341. this._depthMask = value;
  7342. this._isDepthMaskDirty = true;
  7343. },
  7344. enumerable: true,
  7345. configurable: true
  7346. });
  7347. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7348. get: function () {
  7349. return this._depthTest;
  7350. },
  7351. set: function (value) {
  7352. if (this._depthTest === value) {
  7353. return;
  7354. }
  7355. this._depthTest = value;
  7356. this._isDepthTestDirty = true;
  7357. },
  7358. enumerable: true,
  7359. configurable: true
  7360. });
  7361. _DepthCullingState.prototype.reset = function () {
  7362. this._depthMask = true;
  7363. this._depthTest = true;
  7364. this._depthFunc = null;
  7365. this._cullFace = null;
  7366. this._cull = null;
  7367. this._zOffset = 0;
  7368. this._isDepthTestDirty = true;
  7369. this._isDepthMaskDirty = true;
  7370. this._isDepthFuncDirty = false;
  7371. this._isCullFaceDirty = false;
  7372. this._isCullDirty = false;
  7373. this._isZOffsetDirty = false;
  7374. };
  7375. _DepthCullingState.prototype.apply = function (gl) {
  7376. if (!this.isDirty) {
  7377. return;
  7378. }
  7379. // Cull
  7380. if (this._isCullDirty) {
  7381. if (this.cull) {
  7382. gl.enable(gl.CULL_FACE);
  7383. }
  7384. else {
  7385. gl.disable(gl.CULL_FACE);
  7386. }
  7387. this._isCullDirty = false;
  7388. }
  7389. // Cull face
  7390. if (this._isCullFaceDirty) {
  7391. gl.cullFace(this.cullFace);
  7392. this._isCullFaceDirty = false;
  7393. }
  7394. // Depth mask
  7395. if (this._isDepthMaskDirty) {
  7396. gl.depthMask(this.depthMask);
  7397. this._isDepthMaskDirty = false;
  7398. }
  7399. // Depth test
  7400. if (this._isDepthTestDirty) {
  7401. if (this.depthTest) {
  7402. gl.enable(gl.DEPTH_TEST);
  7403. }
  7404. else {
  7405. gl.disable(gl.DEPTH_TEST);
  7406. }
  7407. this._isDepthTestDirty = false;
  7408. }
  7409. // Depth func
  7410. if (this._isDepthFuncDirty) {
  7411. gl.depthFunc(this.depthFunc);
  7412. this._isDepthFuncDirty = false;
  7413. }
  7414. // zOffset
  7415. if (this._isZOffsetDirty) {
  7416. if (this.zOffset) {
  7417. gl.enable(gl.POLYGON_OFFSET_FILL);
  7418. gl.polygonOffset(this.zOffset, 0);
  7419. }
  7420. else {
  7421. gl.disable(gl.POLYGON_OFFSET_FILL);
  7422. }
  7423. this._isZOffsetDirty = false;
  7424. }
  7425. };
  7426. return _DepthCullingState;
  7427. }());
  7428. Internals._DepthCullingState = _DepthCullingState;
  7429. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7430. })(BABYLON || (BABYLON = {}));
  7431. //# sourceMappingURL=babylon.depthCullingState.js.map
  7432. var BABYLON;
  7433. (function (BABYLON) {
  7434. var Internals;
  7435. (function (Internals) {
  7436. var _StencilState = /** @class */ (function () {
  7437. function _StencilState() {
  7438. this._isStencilTestDirty = false;
  7439. this._isStencilMaskDirty = false;
  7440. this._isStencilFuncDirty = false;
  7441. this._isStencilOpDirty = false;
  7442. this.reset();
  7443. }
  7444. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7445. get: function () {
  7446. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7447. },
  7448. enumerable: true,
  7449. configurable: true
  7450. });
  7451. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7452. get: function () {
  7453. return this._stencilFunc;
  7454. },
  7455. set: function (value) {
  7456. if (this._stencilFunc === value) {
  7457. return;
  7458. }
  7459. this._stencilFunc = value;
  7460. this._isStencilFuncDirty = true;
  7461. },
  7462. enumerable: true,
  7463. configurable: true
  7464. });
  7465. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7466. get: function () {
  7467. return this._stencilFuncRef;
  7468. },
  7469. set: function (value) {
  7470. if (this._stencilFuncRef === value) {
  7471. return;
  7472. }
  7473. this._stencilFuncRef = value;
  7474. this._isStencilFuncDirty = true;
  7475. },
  7476. enumerable: true,
  7477. configurable: true
  7478. });
  7479. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7480. get: function () {
  7481. return this._stencilFuncMask;
  7482. },
  7483. set: function (value) {
  7484. if (this._stencilFuncMask === value) {
  7485. return;
  7486. }
  7487. this._stencilFuncMask = value;
  7488. this._isStencilFuncDirty = true;
  7489. },
  7490. enumerable: true,
  7491. configurable: true
  7492. });
  7493. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7494. get: function () {
  7495. return this._stencilOpStencilFail;
  7496. },
  7497. set: function (value) {
  7498. if (this._stencilOpStencilFail === value) {
  7499. return;
  7500. }
  7501. this._stencilOpStencilFail = value;
  7502. this._isStencilOpDirty = true;
  7503. },
  7504. enumerable: true,
  7505. configurable: true
  7506. });
  7507. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7508. get: function () {
  7509. return this._stencilOpDepthFail;
  7510. },
  7511. set: function (value) {
  7512. if (this._stencilOpDepthFail === value) {
  7513. return;
  7514. }
  7515. this._stencilOpDepthFail = value;
  7516. this._isStencilOpDirty = true;
  7517. },
  7518. enumerable: true,
  7519. configurable: true
  7520. });
  7521. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7522. get: function () {
  7523. return this._stencilOpStencilDepthPass;
  7524. },
  7525. set: function (value) {
  7526. if (this._stencilOpStencilDepthPass === value) {
  7527. return;
  7528. }
  7529. this._stencilOpStencilDepthPass = value;
  7530. this._isStencilOpDirty = true;
  7531. },
  7532. enumerable: true,
  7533. configurable: true
  7534. });
  7535. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7536. get: function () {
  7537. return this._stencilMask;
  7538. },
  7539. set: function (value) {
  7540. if (this._stencilMask === value) {
  7541. return;
  7542. }
  7543. this._stencilMask = value;
  7544. this._isStencilMaskDirty = true;
  7545. },
  7546. enumerable: true,
  7547. configurable: true
  7548. });
  7549. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7550. get: function () {
  7551. return this._stencilTest;
  7552. },
  7553. set: function (value) {
  7554. if (this._stencilTest === value) {
  7555. return;
  7556. }
  7557. this._stencilTest = value;
  7558. this._isStencilTestDirty = true;
  7559. },
  7560. enumerable: true,
  7561. configurable: true
  7562. });
  7563. _StencilState.prototype.reset = function () {
  7564. this._stencilTest = false;
  7565. this._stencilMask = 0xFF;
  7566. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7567. this._stencilFuncRef = 1;
  7568. this._stencilFuncMask = 0xFF;
  7569. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7570. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7571. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7572. this._isStencilTestDirty = true;
  7573. this._isStencilMaskDirty = true;
  7574. this._isStencilFuncDirty = true;
  7575. this._isStencilOpDirty = true;
  7576. };
  7577. _StencilState.prototype.apply = function (gl) {
  7578. if (!this.isDirty) {
  7579. return;
  7580. }
  7581. // Stencil test
  7582. if (this._isStencilTestDirty) {
  7583. if (this.stencilTest) {
  7584. gl.enable(gl.STENCIL_TEST);
  7585. }
  7586. else {
  7587. gl.disable(gl.STENCIL_TEST);
  7588. }
  7589. this._isStencilTestDirty = false;
  7590. }
  7591. // Stencil mask
  7592. if (this._isStencilMaskDirty) {
  7593. gl.stencilMask(this.stencilMask);
  7594. this._isStencilMaskDirty = false;
  7595. }
  7596. // Stencil func
  7597. if (this._isStencilFuncDirty) {
  7598. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7599. this._isStencilFuncDirty = false;
  7600. }
  7601. // Stencil op
  7602. if (this._isStencilOpDirty) {
  7603. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7604. this._isStencilOpDirty = false;
  7605. }
  7606. };
  7607. return _StencilState;
  7608. }());
  7609. Internals._StencilState = _StencilState;
  7610. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7611. })(BABYLON || (BABYLON = {}));
  7612. //# sourceMappingURL=babylon.stencilState.js.map
  7613. var BABYLON;
  7614. (function (BABYLON) {
  7615. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7616. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7617. };
  7618. var compileRawShader = function (gl, source, type) {
  7619. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7620. gl.shaderSource(shader, source);
  7621. gl.compileShader(shader);
  7622. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7623. var log = gl.getShaderInfoLog(shader);
  7624. if (log) {
  7625. throw new Error(log);
  7626. }
  7627. }
  7628. if (!shader) {
  7629. throw new Error("Something went wrong while compile the shader.");
  7630. }
  7631. return shader;
  7632. };
  7633. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7634. var magFilter = gl.NEAREST;
  7635. var minFilter = gl.NEAREST;
  7636. switch (samplingMode) {
  7637. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7638. magFilter = gl.LINEAR;
  7639. if (generateMipMaps) {
  7640. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7641. }
  7642. else {
  7643. minFilter = gl.LINEAR;
  7644. }
  7645. break;
  7646. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7647. magFilter = gl.LINEAR;
  7648. if (generateMipMaps) {
  7649. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7650. }
  7651. else {
  7652. minFilter = gl.LINEAR;
  7653. }
  7654. break;
  7655. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7656. magFilter = gl.NEAREST;
  7657. if (generateMipMaps) {
  7658. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7659. }
  7660. else {
  7661. minFilter = gl.NEAREST;
  7662. }
  7663. break;
  7664. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7665. magFilter = gl.NEAREST;
  7666. if (generateMipMaps) {
  7667. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7668. }
  7669. else {
  7670. minFilter = gl.NEAREST;
  7671. }
  7672. break;
  7673. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7674. magFilter = gl.NEAREST;
  7675. if (generateMipMaps) {
  7676. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7677. }
  7678. else {
  7679. minFilter = gl.LINEAR;
  7680. }
  7681. break;
  7682. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7683. magFilter = gl.NEAREST;
  7684. if (generateMipMaps) {
  7685. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7686. }
  7687. else {
  7688. minFilter = gl.LINEAR;
  7689. }
  7690. break;
  7691. case BABYLON.Texture.NEAREST_LINEAR:
  7692. magFilter = gl.NEAREST;
  7693. minFilter = gl.LINEAR;
  7694. break;
  7695. case BABYLON.Texture.NEAREST_NEAREST:
  7696. magFilter = gl.NEAREST;
  7697. minFilter = gl.NEAREST;
  7698. break;
  7699. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7700. magFilter = gl.LINEAR;
  7701. if (generateMipMaps) {
  7702. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7703. }
  7704. else {
  7705. minFilter = gl.NEAREST;
  7706. }
  7707. break;
  7708. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7709. magFilter = gl.LINEAR;
  7710. if (generateMipMaps) {
  7711. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7712. }
  7713. else {
  7714. minFilter = gl.NEAREST;
  7715. }
  7716. break;
  7717. case BABYLON.Texture.LINEAR_LINEAR:
  7718. magFilter = gl.LINEAR;
  7719. minFilter = gl.LINEAR;
  7720. break;
  7721. case BABYLON.Texture.LINEAR_NEAREST:
  7722. magFilter = gl.LINEAR;
  7723. minFilter = gl.NEAREST;
  7724. break;
  7725. }
  7726. return {
  7727. min: minFilter,
  7728. mag: magFilter
  7729. };
  7730. };
  7731. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7732. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7733. var img;
  7734. var onload = function () {
  7735. loadedImages[index] = img;
  7736. loadedImages._internalCount++;
  7737. if (scene) {
  7738. scene._removePendingData(img);
  7739. }
  7740. if (loadedImages._internalCount === 6) {
  7741. onfinish(loadedImages);
  7742. }
  7743. };
  7744. var onerror = function (message, exception) {
  7745. if (scene) {
  7746. scene._removePendingData(img);
  7747. }
  7748. if (onErrorCallBack) {
  7749. onErrorCallBack(message, exception);
  7750. }
  7751. };
  7752. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7753. if (scene) {
  7754. scene._addPendingData(img);
  7755. }
  7756. };
  7757. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7758. if (onError === void 0) { onError = null; }
  7759. var loadedImages = [];
  7760. loadedImages._internalCount = 0;
  7761. for (var index = 0; index < 6; index++) {
  7762. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7763. }
  7764. };
  7765. var BufferPointer = /** @class */ (function () {
  7766. function BufferPointer() {
  7767. }
  7768. return BufferPointer;
  7769. }());
  7770. var InstancingAttributeInfo = /** @class */ (function () {
  7771. function InstancingAttributeInfo() {
  7772. }
  7773. return InstancingAttributeInfo;
  7774. }());
  7775. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7776. /**
  7777. * Define options used to create a render target texture
  7778. */
  7779. var RenderTargetCreationOptions = /** @class */ (function () {
  7780. function RenderTargetCreationOptions() {
  7781. }
  7782. return RenderTargetCreationOptions;
  7783. }());
  7784. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7785. /**
  7786. * Regroup several parameters relative to the browser in use
  7787. */
  7788. var EngineCapabilities = /** @class */ (function () {
  7789. function EngineCapabilities() {
  7790. }
  7791. return EngineCapabilities;
  7792. }());
  7793. BABYLON.EngineCapabilities = EngineCapabilities;
  7794. /**
  7795. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7796. */
  7797. var Engine = /** @class */ (function () {
  7798. /**
  7799. * @constructor
  7800. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7801. * @param {boolean} [antialias] - enable antialias
  7802. * @param options - further options to be sent to the getContext function
  7803. */
  7804. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7805. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7806. var _this = this;
  7807. // Public members
  7808. this.forcePOTTextures = false;
  7809. this.isFullscreen = false;
  7810. this.isPointerLock = false;
  7811. this.cullBackFaces = true;
  7812. this.renderEvenInBackground = true;
  7813. this.preventCacheWipeBetweenFrames = false;
  7814. // To enable/disable IDB support and avoid XHR on .manifest
  7815. this.enableOfflineSupport = false;
  7816. this.scenes = new Array();
  7817. this.postProcesses = new Array();
  7818. // Observables
  7819. /**
  7820. * Observable event triggered each time the rendering canvas is resized
  7821. */
  7822. this.onResizeObservable = new BABYLON.Observable();
  7823. /**
  7824. * Observable event triggered each time the canvas loses focus
  7825. */
  7826. this.onCanvasBlurObservable = new BABYLON.Observable();
  7827. /**
  7828. * Observable event triggered each time the canvas gains focus
  7829. */
  7830. this.onCanvasFocusObservable = new BABYLON.Observable();
  7831. /**
  7832. * Observable event triggered each time the canvas receives pointerout event
  7833. */
  7834. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7835. /**
  7836. * Observable event triggered before each texture is initialized
  7837. */
  7838. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7839. //WebVR
  7840. this._vrDisplay = undefined;
  7841. this._vrSupported = false;
  7842. this._vrExclusivePointerMode = false;
  7843. // Uniform buffers list
  7844. this.disableUniformBuffers = false;
  7845. this._uniformBuffers = new Array();
  7846. // Observables
  7847. /**
  7848. * Observable raised when the engine begins a new frame
  7849. */
  7850. this.onBeginFrameObservable = new BABYLON.Observable();
  7851. /**
  7852. * Observable raised when the engine ends the current frame
  7853. */
  7854. this.onEndFrameObservable = new BABYLON.Observable();
  7855. /**
  7856. * Observable raised when the engine is about to compile a shader
  7857. */
  7858. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7859. /**
  7860. * Observable raised when the engine has jsut compiled a shader
  7861. */
  7862. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7863. this._windowIsBackground = false;
  7864. this._webGLVersion = 1.0;
  7865. this._badOS = false;
  7866. this._badDesktopOS = false;
  7867. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7868. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7869. this.onVRRequestPresentStart = new BABYLON.Observable();
  7870. this._colorWrite = true;
  7871. this._drawCalls = new BABYLON.PerfCounter();
  7872. this._renderingQueueLaunched = false;
  7873. this._activeRenderLoops = new Array();
  7874. // Deterministic lockstepMaxSteps
  7875. this._deterministicLockstep = false;
  7876. this._lockstepMaxSteps = 4;
  7877. // Lost context
  7878. this.onContextLostObservable = new BABYLON.Observable();
  7879. this.onContextRestoredObservable = new BABYLON.Observable();
  7880. this._contextWasLost = false;
  7881. this._doNotHandleContextLost = false;
  7882. // FPS
  7883. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7884. this._fps = 60;
  7885. this._deltaTime = 0;
  7886. /**
  7887. * Turn this value on if you want to pause FPS computation when in background
  7888. */
  7889. this.disablePerformanceMonitorInBackground = false;
  7890. // States
  7891. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7892. this._stencilState = new BABYLON.Internals._StencilState();
  7893. this._alphaState = new BABYLON.Internals._AlphaState();
  7894. this._alphaMode = Engine.ALPHA_DISABLE;
  7895. // Cache
  7896. this._internalTexturesCache = new Array();
  7897. this._activeTexturesCache = {};
  7898. this._compiledEffects = {};
  7899. this._vertexAttribArraysEnabled = [];
  7900. this._uintIndicesCurrentlySet = false;
  7901. this._currentBoundBuffer = new Array();
  7902. this._currentBufferPointers = new Array();
  7903. this._currentInstanceLocations = new Array();
  7904. this._currentInstanceBuffers = new Array();
  7905. this._vaoRecordInProgress = false;
  7906. this._mustWipeVertexAttributes = false;
  7907. // Hardware supported Compressed Textures
  7908. this._texturesSupported = new Array();
  7909. this._onVRFullScreenTriggered = function () {
  7910. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7911. //get the old size before we change
  7912. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7913. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7914. //get the width and height, change the render size
  7915. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7916. _this.setHardwareScalingLevel(1);
  7917. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7918. }
  7919. else {
  7920. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7921. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7922. }
  7923. };
  7924. var canvas = null;
  7925. Engine.Instances.push(this);
  7926. if (!canvasOrContext) {
  7927. return;
  7928. }
  7929. options = options || {};
  7930. if (canvasOrContext.getContext) {
  7931. canvas = canvasOrContext;
  7932. this._renderingCanvas = canvas;
  7933. if (antialias != null) {
  7934. options.antialias = antialias;
  7935. }
  7936. if (options.deterministicLockstep === undefined) {
  7937. options.deterministicLockstep = false;
  7938. }
  7939. if (options.lockstepMaxSteps === undefined) {
  7940. options.lockstepMaxSteps = 4;
  7941. }
  7942. if (options.preserveDrawingBuffer === undefined) {
  7943. options.preserveDrawingBuffer = false;
  7944. }
  7945. if (options.audioEngine === undefined) {
  7946. options.audioEngine = true;
  7947. }
  7948. if (options.stencil === undefined) {
  7949. options.stencil = true;
  7950. }
  7951. this._deterministicLockstep = options.deterministicLockstep;
  7952. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7953. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  7954. // GL
  7955. if (!options.disableWebGL2Support) {
  7956. try {
  7957. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7958. if (this._gl) {
  7959. this._webGLVersion = 2.0;
  7960. }
  7961. }
  7962. catch (e) {
  7963. // Do nothing
  7964. }
  7965. }
  7966. if (!this._gl) {
  7967. if (!canvas) {
  7968. throw new Error("The provided canvas is null or undefined.");
  7969. }
  7970. try {
  7971. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7972. }
  7973. catch (e) {
  7974. throw new Error("WebGL not supported");
  7975. }
  7976. }
  7977. if (!this._gl) {
  7978. throw new Error("WebGL not supported");
  7979. }
  7980. this._onCanvasFocus = function () {
  7981. _this.onCanvasFocusObservable.notifyObservers(_this);
  7982. };
  7983. this._onCanvasBlur = function () {
  7984. _this.onCanvasBlurObservable.notifyObservers(_this);
  7985. };
  7986. canvas.addEventListener("focus", this._onCanvasFocus);
  7987. canvas.addEventListener("blur", this._onCanvasBlur);
  7988. this._onBlur = function () {
  7989. if (_this.disablePerformanceMonitorInBackground) {
  7990. _this._performanceMonitor.disable();
  7991. }
  7992. _this._windowIsBackground = true;
  7993. };
  7994. this._onFocus = function () {
  7995. if (_this.disablePerformanceMonitorInBackground) {
  7996. _this._performanceMonitor.enable();
  7997. }
  7998. _this._windowIsBackground = false;
  7999. };
  8000. this._onCanvasPointerOut = function () {
  8001. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8002. };
  8003. window.addEventListener("blur", this._onBlur);
  8004. window.addEventListener("focus", this._onFocus);
  8005. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8006. // Context lost
  8007. if (!this._doNotHandleContextLost) {
  8008. this._onContextLost = function (evt) {
  8009. evt.preventDefault();
  8010. _this._contextWasLost = true;
  8011. BABYLON.Tools.Warn("WebGL context lost.");
  8012. _this.onContextLostObservable.notifyObservers(_this);
  8013. };
  8014. this._onContextRestored = function (evt) {
  8015. // Adding a timeout to avoid race condition at browser level
  8016. setTimeout(function () {
  8017. // Rebuild gl context
  8018. _this._initGLContext();
  8019. // Rebuild effects
  8020. _this._rebuildEffects();
  8021. // Rebuild textures
  8022. _this._rebuildInternalTextures();
  8023. // Rebuild buffers
  8024. _this._rebuildBuffers();
  8025. // Cache
  8026. _this.wipeCaches(true);
  8027. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8028. _this.onContextRestoredObservable.notifyObservers(_this);
  8029. _this._contextWasLost = false;
  8030. }, 0);
  8031. };
  8032. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8033. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8034. }
  8035. }
  8036. else {
  8037. this._gl = canvasOrContext;
  8038. this._renderingCanvas = this._gl.canvas;
  8039. if (this._gl.renderbufferStorageMultisample) {
  8040. this._webGLVersion = 2.0;
  8041. }
  8042. options.stencil = this._gl.getContextAttributes().stencil;
  8043. }
  8044. // Viewport
  8045. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8046. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8047. this.resize();
  8048. this._isStencilEnable = options.stencil ? true : false;
  8049. this._initGLContext();
  8050. if (canvas) {
  8051. // Fullscreen
  8052. this._onFullscreenChange = function () {
  8053. if (document.fullscreen !== undefined) {
  8054. _this.isFullscreen = document.fullscreen;
  8055. }
  8056. else if (document.mozFullScreen !== undefined) {
  8057. _this.isFullscreen = document.mozFullScreen;
  8058. }
  8059. else if (document.webkitIsFullScreen !== undefined) {
  8060. _this.isFullscreen = document.webkitIsFullScreen;
  8061. }
  8062. else if (document.msIsFullScreen !== undefined) {
  8063. _this.isFullscreen = document.msIsFullScreen;
  8064. }
  8065. // Pointer lock
  8066. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8067. canvas.requestPointerLock = canvas.requestPointerLock ||
  8068. canvas.msRequestPointerLock ||
  8069. canvas.mozRequestPointerLock ||
  8070. canvas.webkitRequestPointerLock;
  8071. if (canvas.requestPointerLock) {
  8072. canvas.requestPointerLock();
  8073. }
  8074. }
  8075. };
  8076. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8077. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8078. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8079. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8080. // Pointer lock
  8081. this._onPointerLockChange = function () {
  8082. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8083. document.webkitPointerLockElement === canvas ||
  8084. document.msPointerLockElement === canvas ||
  8085. document.pointerLockElement === canvas);
  8086. };
  8087. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8088. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8089. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8090. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8091. this._onVRDisplayPointerRestricted = function () {
  8092. if (canvas) {
  8093. canvas.requestPointerLock();
  8094. }
  8095. };
  8096. this._onVRDisplayPointerUnrestricted = function () {
  8097. document.exitPointerLock();
  8098. };
  8099. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8100. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8101. }
  8102. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8103. Engine.audioEngine = new BABYLON.AudioEngine();
  8104. }
  8105. // Prepare buffer pointers
  8106. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8107. this._currentBufferPointers[i] = new BufferPointer();
  8108. }
  8109. // Load WebVR Devices
  8110. if (options.autoEnableWebVR) {
  8111. this.initWebVR();
  8112. }
  8113. // Detect if we are running on a faulty buggy OS.
  8114. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8115. // Detect if we are running on a faulty buggy desktop OS.
  8116. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8117. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8118. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8119. }
  8120. Object.defineProperty(Engine, "LastCreatedEngine", {
  8121. get: function () {
  8122. if (Engine.Instances.length === 0) {
  8123. return null;
  8124. }
  8125. return Engine.Instances[Engine.Instances.length - 1];
  8126. },
  8127. enumerable: true,
  8128. configurable: true
  8129. });
  8130. Object.defineProperty(Engine, "LastCreatedScene", {
  8131. get: function () {
  8132. var lastCreatedEngine = Engine.LastCreatedEngine;
  8133. if (!lastCreatedEngine) {
  8134. return null;
  8135. }
  8136. if (lastCreatedEngine.scenes.length === 0) {
  8137. return null;
  8138. }
  8139. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8140. },
  8141. enumerable: true,
  8142. configurable: true
  8143. });
  8144. /**
  8145. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8146. */
  8147. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8148. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8149. var engine = Engine.Instances[engineIndex];
  8150. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8151. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8152. }
  8153. }
  8154. };
  8155. Object.defineProperty(Engine, "NEVER", {
  8156. get: function () {
  8157. return Engine._NEVER;
  8158. },
  8159. enumerable: true,
  8160. configurable: true
  8161. });
  8162. Object.defineProperty(Engine, "ALWAYS", {
  8163. get: function () {
  8164. return Engine._ALWAYS;
  8165. },
  8166. enumerable: true,
  8167. configurable: true
  8168. });
  8169. Object.defineProperty(Engine, "LESS", {
  8170. get: function () {
  8171. return Engine._LESS;
  8172. },
  8173. enumerable: true,
  8174. configurable: true
  8175. });
  8176. Object.defineProperty(Engine, "EQUAL", {
  8177. get: function () {
  8178. return Engine._EQUAL;
  8179. },
  8180. enumerable: true,
  8181. configurable: true
  8182. });
  8183. Object.defineProperty(Engine, "LEQUAL", {
  8184. get: function () {
  8185. return Engine._LEQUAL;
  8186. },
  8187. enumerable: true,
  8188. configurable: true
  8189. });
  8190. Object.defineProperty(Engine, "GREATER", {
  8191. get: function () {
  8192. return Engine._GREATER;
  8193. },
  8194. enumerable: true,
  8195. configurable: true
  8196. });
  8197. Object.defineProperty(Engine, "GEQUAL", {
  8198. get: function () {
  8199. return Engine._GEQUAL;
  8200. },
  8201. enumerable: true,
  8202. configurable: true
  8203. });
  8204. Object.defineProperty(Engine, "NOTEQUAL", {
  8205. get: function () {
  8206. return Engine._NOTEQUAL;
  8207. },
  8208. enumerable: true,
  8209. configurable: true
  8210. });
  8211. Object.defineProperty(Engine, "KEEP", {
  8212. get: function () {
  8213. return Engine._KEEP;
  8214. },
  8215. enumerable: true,
  8216. configurable: true
  8217. });
  8218. Object.defineProperty(Engine, "REPLACE", {
  8219. get: function () {
  8220. return Engine._REPLACE;
  8221. },
  8222. enumerable: true,
  8223. configurable: true
  8224. });
  8225. Object.defineProperty(Engine, "INCR", {
  8226. get: function () {
  8227. return Engine._INCR;
  8228. },
  8229. enumerable: true,
  8230. configurable: true
  8231. });
  8232. Object.defineProperty(Engine, "DECR", {
  8233. get: function () {
  8234. return Engine._DECR;
  8235. },
  8236. enumerable: true,
  8237. configurable: true
  8238. });
  8239. Object.defineProperty(Engine, "INVERT", {
  8240. get: function () {
  8241. return Engine._INVERT;
  8242. },
  8243. enumerable: true,
  8244. configurable: true
  8245. });
  8246. Object.defineProperty(Engine, "INCR_WRAP", {
  8247. get: function () {
  8248. return Engine._INCR_WRAP;
  8249. },
  8250. enumerable: true,
  8251. configurable: true
  8252. });
  8253. Object.defineProperty(Engine, "DECR_WRAP", {
  8254. get: function () {
  8255. return Engine._DECR_WRAP;
  8256. },
  8257. enumerable: true,
  8258. configurable: true
  8259. });
  8260. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8261. get: function () {
  8262. return Engine._ALPHA_DISABLE;
  8263. },
  8264. enumerable: true,
  8265. configurable: true
  8266. });
  8267. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8268. get: function () {
  8269. return Engine._ALPHA_ONEONE;
  8270. },
  8271. enumerable: true,
  8272. configurable: true
  8273. });
  8274. Object.defineProperty(Engine, "ALPHA_ADD", {
  8275. get: function () {
  8276. return Engine._ALPHA_ADD;
  8277. },
  8278. enumerable: true,
  8279. configurable: true
  8280. });
  8281. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8282. get: function () {
  8283. return Engine._ALPHA_COMBINE;
  8284. },
  8285. enumerable: true,
  8286. configurable: true
  8287. });
  8288. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8289. get: function () {
  8290. return Engine._ALPHA_SUBTRACT;
  8291. },
  8292. enumerable: true,
  8293. configurable: true
  8294. });
  8295. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8296. get: function () {
  8297. return Engine._ALPHA_MULTIPLY;
  8298. },
  8299. enumerable: true,
  8300. configurable: true
  8301. });
  8302. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8303. get: function () {
  8304. return Engine._ALPHA_MAXIMIZED;
  8305. },
  8306. enumerable: true,
  8307. configurable: true
  8308. });
  8309. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8310. get: function () {
  8311. return Engine._ALPHA_PREMULTIPLIED;
  8312. },
  8313. enumerable: true,
  8314. configurable: true
  8315. });
  8316. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8317. get: function () {
  8318. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8319. },
  8320. enumerable: true,
  8321. configurable: true
  8322. });
  8323. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8324. get: function () {
  8325. return Engine._ALPHA_INTERPOLATE;
  8326. },
  8327. enumerable: true,
  8328. configurable: true
  8329. });
  8330. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8331. get: function () {
  8332. return Engine._ALPHA_SCREENMODE;
  8333. },
  8334. enumerable: true,
  8335. configurable: true
  8336. });
  8337. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8338. get: function () {
  8339. return Engine._DELAYLOADSTATE_NONE;
  8340. },
  8341. enumerable: true,
  8342. configurable: true
  8343. });
  8344. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8345. get: function () {
  8346. return Engine._DELAYLOADSTATE_LOADED;
  8347. },
  8348. enumerable: true,
  8349. configurable: true
  8350. });
  8351. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8352. get: function () {
  8353. return Engine._DELAYLOADSTATE_LOADING;
  8354. },
  8355. enumerable: true,
  8356. configurable: true
  8357. });
  8358. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8359. get: function () {
  8360. return Engine._DELAYLOADSTATE_NOTLOADED;
  8361. },
  8362. enumerable: true,
  8363. configurable: true
  8364. });
  8365. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8366. get: function () {
  8367. return Engine._TEXTUREFORMAT_ALPHA;
  8368. },
  8369. enumerable: true,
  8370. configurable: true
  8371. });
  8372. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8373. get: function () {
  8374. return Engine._TEXTUREFORMAT_LUMINANCE;
  8375. },
  8376. enumerable: true,
  8377. configurable: true
  8378. });
  8379. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8380. get: function () {
  8381. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8382. },
  8383. enumerable: true,
  8384. configurable: true
  8385. });
  8386. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8387. get: function () {
  8388. return Engine._TEXTUREFORMAT_RGB;
  8389. },
  8390. enumerable: true,
  8391. configurable: true
  8392. });
  8393. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8394. get: function () {
  8395. return Engine._TEXTUREFORMAT_RGBA;
  8396. },
  8397. enumerable: true,
  8398. configurable: true
  8399. });
  8400. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8401. get: function () {
  8402. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8403. },
  8404. enumerable: true,
  8405. configurable: true
  8406. });
  8407. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8408. get: function () {
  8409. return Engine._TEXTURETYPE_FLOAT;
  8410. },
  8411. enumerable: true,
  8412. configurable: true
  8413. });
  8414. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8415. get: function () {
  8416. return Engine._TEXTURETYPE_HALF_FLOAT;
  8417. },
  8418. enumerable: true,
  8419. configurable: true
  8420. });
  8421. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8422. get: function () {
  8423. return Engine._SCALEMODE_FLOOR;
  8424. },
  8425. enumerable: true,
  8426. configurable: true
  8427. });
  8428. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8429. get: function () {
  8430. return Engine._SCALEMODE_NEAREST;
  8431. },
  8432. enumerable: true,
  8433. configurable: true
  8434. });
  8435. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8436. get: function () {
  8437. return Engine._SCALEMODE_CEILING;
  8438. },
  8439. enumerable: true,
  8440. configurable: true
  8441. });
  8442. Object.defineProperty(Engine, "Version", {
  8443. get: function () {
  8444. return "3.1-alpha";
  8445. },
  8446. enumerable: true,
  8447. configurable: true
  8448. });
  8449. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8450. get: function () {
  8451. return this._vrExclusivePointerMode;
  8452. },
  8453. enumerable: true,
  8454. configurable: true
  8455. });
  8456. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8457. get: function () {
  8458. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8459. },
  8460. enumerable: true,
  8461. configurable: true
  8462. });
  8463. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8464. get: function () {
  8465. return this._webGLVersion < 2 || this.forcePOTTextures;
  8466. },
  8467. enumerable: true,
  8468. configurable: true
  8469. });
  8470. Object.defineProperty(Engine.prototype, "badOS", {
  8471. get: function () {
  8472. return this._badOS;
  8473. },
  8474. enumerable: true,
  8475. configurable: true
  8476. });
  8477. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8478. get: function () {
  8479. return this._badDesktopOS;
  8480. },
  8481. enumerable: true,
  8482. configurable: true
  8483. });
  8484. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8485. get: function () {
  8486. return this._performanceMonitor;
  8487. },
  8488. enumerable: true,
  8489. configurable: true
  8490. });
  8491. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8492. get: function () {
  8493. return this._texturesSupported;
  8494. },
  8495. enumerable: true,
  8496. configurable: true
  8497. });
  8498. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8499. get: function () {
  8500. return this._textureFormatInUse;
  8501. },
  8502. enumerable: true,
  8503. configurable: true
  8504. });
  8505. Object.defineProperty(Engine.prototype, "currentViewport", {
  8506. get: function () {
  8507. return this._cachedViewport;
  8508. },
  8509. enumerable: true,
  8510. configurable: true
  8511. });
  8512. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8513. // Empty texture
  8514. get: function () {
  8515. if (!this._emptyTexture) {
  8516. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8517. }
  8518. return this._emptyTexture;
  8519. },
  8520. enumerable: true,
  8521. configurable: true
  8522. });
  8523. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8524. get: function () {
  8525. if (!this._emptyTexture3D) {
  8526. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8527. }
  8528. return this._emptyTexture3D;
  8529. },
  8530. enumerable: true,
  8531. configurable: true
  8532. });
  8533. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8534. get: function () {
  8535. if (!this._emptyCubeTexture) {
  8536. var faceData = new Uint8Array(4);
  8537. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8538. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8539. }
  8540. return this._emptyCubeTexture;
  8541. },
  8542. enumerable: true,
  8543. configurable: true
  8544. });
  8545. Engine.prototype._rebuildInternalTextures = function () {
  8546. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8547. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8548. var internalTexture = currentState_1[_i];
  8549. internalTexture._rebuild();
  8550. }
  8551. };
  8552. Engine.prototype._rebuildEffects = function () {
  8553. for (var key in this._compiledEffects) {
  8554. var effect = this._compiledEffects[key];
  8555. effect._prepareEffect();
  8556. }
  8557. BABYLON.Effect.ResetCache();
  8558. };
  8559. Engine.prototype._rebuildBuffers = function () {
  8560. // Index / Vertex
  8561. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8562. var scene = _a[_i];
  8563. scene.resetCachedMaterial();
  8564. scene._rebuildGeometries();
  8565. scene._rebuildTextures();
  8566. }
  8567. // Uniforms
  8568. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8569. var uniformBuffer = _c[_b];
  8570. uniformBuffer._rebuild();
  8571. }
  8572. };
  8573. Engine.prototype._initGLContext = function () {
  8574. // Caps
  8575. this._caps = new EngineCapabilities();
  8576. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8577. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8578. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8579. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8580. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8581. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8582. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8583. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8584. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8585. // Infos
  8586. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8587. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8588. if (rendererInfo != null) {
  8589. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8590. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8591. }
  8592. if (!this._glVendor) {
  8593. this._glVendor = "Unknown vendor";
  8594. }
  8595. if (!this._glRenderer) {
  8596. this._glRenderer = "Unknown renderer";
  8597. }
  8598. // Constants
  8599. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8600. if (this._gl.RGBA16F !== 0x881A) {
  8601. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8602. }
  8603. if (this._gl.RGBA32F !== 0x8814) {
  8604. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8605. }
  8606. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8607. this._gl.DEPTH24_STENCIL8 = 35056;
  8608. }
  8609. // Extensions
  8610. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8611. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8612. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8613. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8614. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8615. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8616. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8617. 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');
  8618. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8619. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8620. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8621. this._caps.highPrecisionShaderSupported = true;
  8622. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8623. if (this._caps.timerQuery) {
  8624. if (this._webGLVersion === 1) {
  8625. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8626. }
  8627. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8628. }
  8629. // Checks if some of the format renders first to allow the use of webgl inspector.
  8630. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8631. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8632. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8633. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8634. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8635. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8636. if (this._webGLVersion > 1) {
  8637. this._gl.HALF_FLOAT_OES = 0x140B;
  8638. }
  8639. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8640. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8641. // Draw buffers
  8642. if (this._webGLVersion > 1) {
  8643. this._caps.drawBuffersExtension = true;
  8644. }
  8645. else {
  8646. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8647. if (drawBuffersExtension !== null) {
  8648. this._caps.drawBuffersExtension = true;
  8649. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8650. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8651. for (var i = 0; i < 16; i++) {
  8652. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8653. }
  8654. }
  8655. else {
  8656. this._caps.drawBuffersExtension = false;
  8657. }
  8658. }
  8659. // Depth Texture
  8660. if (this._webGLVersion > 1) {
  8661. this._caps.depthTextureExtension = true;
  8662. }
  8663. else {
  8664. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8665. if (depthTextureExtension != null) {
  8666. this._caps.depthTextureExtension = true;
  8667. }
  8668. }
  8669. // Vertex array object
  8670. if (this._webGLVersion > 1) {
  8671. this._caps.vertexArrayObject = true;
  8672. }
  8673. else {
  8674. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8675. if (vertexArrayObjectExtension != null) {
  8676. this._caps.vertexArrayObject = true;
  8677. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8678. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8679. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8680. }
  8681. else {
  8682. this._caps.vertexArrayObject = false;
  8683. }
  8684. }
  8685. // Instances count
  8686. if (this._webGLVersion > 1) {
  8687. this._caps.instancedArrays = true;
  8688. }
  8689. else {
  8690. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8691. if (instanceExtension != null) {
  8692. this._caps.instancedArrays = true;
  8693. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8694. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8695. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8696. }
  8697. else {
  8698. this._caps.instancedArrays = false;
  8699. }
  8700. }
  8701. // Intelligently add supported compressed formats in order to check for.
  8702. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8703. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8704. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8705. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8706. if (this._caps.astc)
  8707. this.texturesSupported.push('-astc.ktx');
  8708. if (this._caps.s3tc)
  8709. this.texturesSupported.push('-dxt.ktx');
  8710. if (this._caps.pvrtc)
  8711. this.texturesSupported.push('-pvrtc.ktx');
  8712. if (this._caps.etc2)
  8713. this.texturesSupported.push('-etc2.ktx');
  8714. if (this._caps.etc1)
  8715. this.texturesSupported.push('-etc1.ktx');
  8716. if (this._gl.getShaderPrecisionFormat) {
  8717. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8718. if (highp) {
  8719. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8720. }
  8721. }
  8722. // Depth buffer
  8723. this.setDepthBuffer(true);
  8724. this.setDepthFunctionToLessOrEqual();
  8725. this.setDepthWrite(true);
  8726. };
  8727. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8728. get: function () {
  8729. return this._webGLVersion;
  8730. },
  8731. enumerable: true,
  8732. configurable: true
  8733. });
  8734. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8735. /**
  8736. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8737. */
  8738. get: function () {
  8739. return this._isStencilEnable;
  8740. },
  8741. enumerable: true,
  8742. configurable: true
  8743. });
  8744. Engine.prototype._prepareWorkingCanvas = function () {
  8745. if (this._workingCanvas) {
  8746. return;
  8747. }
  8748. this._workingCanvas = document.createElement("canvas");
  8749. var context = this._workingCanvas.getContext("2d");
  8750. if (context) {
  8751. this._workingContext = context;
  8752. }
  8753. };
  8754. Engine.prototype.resetTextureCache = function () {
  8755. for (var key in this._activeTexturesCache) {
  8756. this._activeTexturesCache[key] = null;
  8757. }
  8758. };
  8759. Engine.prototype.isDeterministicLockStep = function () {
  8760. return this._deterministicLockstep;
  8761. };
  8762. Engine.prototype.getLockstepMaxSteps = function () {
  8763. return this._lockstepMaxSteps;
  8764. };
  8765. Engine.prototype.getGlInfo = function () {
  8766. return {
  8767. vendor: this._glVendor,
  8768. renderer: this._glRenderer,
  8769. version: this._glVersion
  8770. };
  8771. };
  8772. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8773. if (useScreen === void 0) { useScreen = false; }
  8774. var viewport = camera.viewport;
  8775. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8776. };
  8777. Engine.prototype.getRenderWidth = function (useScreen) {
  8778. if (useScreen === void 0) { useScreen = false; }
  8779. if (!useScreen && this._currentRenderTarget) {
  8780. return this._currentRenderTarget.width;
  8781. }
  8782. return this._gl.drawingBufferWidth;
  8783. };
  8784. Engine.prototype.getRenderHeight = function (useScreen) {
  8785. if (useScreen === void 0) { useScreen = false; }
  8786. if (!useScreen && this._currentRenderTarget) {
  8787. return this._currentRenderTarget.height;
  8788. }
  8789. return this._gl.drawingBufferHeight;
  8790. };
  8791. Engine.prototype.getRenderingCanvas = function () {
  8792. return this._renderingCanvas;
  8793. };
  8794. Engine.prototype.getRenderingCanvasClientRect = function () {
  8795. if (!this._renderingCanvas) {
  8796. return null;
  8797. }
  8798. return this._renderingCanvas.getBoundingClientRect();
  8799. };
  8800. Engine.prototype.setHardwareScalingLevel = function (level) {
  8801. this._hardwareScalingLevel = level;
  8802. this.resize();
  8803. };
  8804. Engine.prototype.getHardwareScalingLevel = function () {
  8805. return this._hardwareScalingLevel;
  8806. };
  8807. Engine.prototype.getLoadedTexturesCache = function () {
  8808. return this._internalTexturesCache;
  8809. };
  8810. Engine.prototype.getCaps = function () {
  8811. return this._caps;
  8812. };
  8813. Object.defineProperty(Engine.prototype, "drawCalls", {
  8814. /** The number of draw calls submitted last frame */
  8815. get: function () {
  8816. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8817. return 0;
  8818. },
  8819. enumerable: true,
  8820. configurable: true
  8821. });
  8822. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8823. get: function () {
  8824. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8825. return null;
  8826. },
  8827. enumerable: true,
  8828. configurable: true
  8829. });
  8830. Engine.prototype.getDepthFunction = function () {
  8831. return this._depthCullingState.depthFunc;
  8832. };
  8833. Engine.prototype.setDepthFunction = function (depthFunc) {
  8834. this._depthCullingState.depthFunc = depthFunc;
  8835. };
  8836. Engine.prototype.setDepthFunctionToGreater = function () {
  8837. this._depthCullingState.depthFunc = this._gl.GREATER;
  8838. };
  8839. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8840. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8841. };
  8842. Engine.prototype.setDepthFunctionToLess = function () {
  8843. this._depthCullingState.depthFunc = this._gl.LESS;
  8844. };
  8845. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8846. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8847. };
  8848. Engine.prototype.getStencilBuffer = function () {
  8849. return this._stencilState.stencilTest;
  8850. };
  8851. Engine.prototype.setStencilBuffer = function (enable) {
  8852. this._stencilState.stencilTest = enable;
  8853. };
  8854. Engine.prototype.getStencilMask = function () {
  8855. return this._stencilState.stencilMask;
  8856. };
  8857. Engine.prototype.setStencilMask = function (mask) {
  8858. this._stencilState.stencilMask = mask;
  8859. };
  8860. Engine.prototype.getStencilFunction = function () {
  8861. return this._stencilState.stencilFunc;
  8862. };
  8863. Engine.prototype.getStencilFunctionReference = function () {
  8864. return this._stencilState.stencilFuncRef;
  8865. };
  8866. Engine.prototype.getStencilFunctionMask = function () {
  8867. return this._stencilState.stencilFuncMask;
  8868. };
  8869. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8870. this._stencilState.stencilFunc = stencilFunc;
  8871. };
  8872. Engine.prototype.setStencilFunctionReference = function (reference) {
  8873. this._stencilState.stencilFuncRef = reference;
  8874. };
  8875. Engine.prototype.setStencilFunctionMask = function (mask) {
  8876. this._stencilState.stencilFuncMask = mask;
  8877. };
  8878. Engine.prototype.getStencilOperationFail = function () {
  8879. return this._stencilState.stencilOpStencilFail;
  8880. };
  8881. Engine.prototype.getStencilOperationDepthFail = function () {
  8882. return this._stencilState.stencilOpDepthFail;
  8883. };
  8884. Engine.prototype.getStencilOperationPass = function () {
  8885. return this._stencilState.stencilOpStencilDepthPass;
  8886. };
  8887. Engine.prototype.setStencilOperationFail = function (operation) {
  8888. this._stencilState.stencilOpStencilFail = operation;
  8889. };
  8890. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8891. this._stencilState.stencilOpDepthFail = operation;
  8892. };
  8893. Engine.prototype.setStencilOperationPass = function (operation) {
  8894. this._stencilState.stencilOpStencilDepthPass = operation;
  8895. };
  8896. Engine.prototype.setDitheringState = function (value) {
  8897. if (value) {
  8898. this._gl.enable(this._gl.DITHER);
  8899. }
  8900. else {
  8901. this._gl.disable(this._gl.DITHER);
  8902. }
  8903. };
  8904. Engine.prototype.setRasterizerState = function (value) {
  8905. if (value) {
  8906. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  8907. }
  8908. else {
  8909. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  8910. }
  8911. };
  8912. /**
  8913. * stop executing a render loop function and remove it from the execution array
  8914. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8915. */
  8916. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8917. if (!renderFunction) {
  8918. this._activeRenderLoops = [];
  8919. return;
  8920. }
  8921. var index = this._activeRenderLoops.indexOf(renderFunction);
  8922. if (index >= 0) {
  8923. this._activeRenderLoops.splice(index, 1);
  8924. }
  8925. };
  8926. Engine.prototype._renderLoop = function () {
  8927. if (!this._contextWasLost) {
  8928. var shouldRender = true;
  8929. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8930. shouldRender = false;
  8931. }
  8932. if (shouldRender) {
  8933. // Start new frame
  8934. this.beginFrame();
  8935. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8936. var renderFunction = this._activeRenderLoops[index];
  8937. renderFunction();
  8938. }
  8939. // Present
  8940. this.endFrame();
  8941. }
  8942. }
  8943. if (this._activeRenderLoops.length > 0) {
  8944. // Register new frame
  8945. var requester = null;
  8946. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8947. requester = this._vrDisplay;
  8948. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8949. }
  8950. else {
  8951. this._renderingQueueLaunched = false;
  8952. }
  8953. };
  8954. /**
  8955. * Register and execute a render loop. The engine can have more than one render function.
  8956. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8957. * @example
  8958. * engine.runRenderLoop(function () {
  8959. * scene.render()
  8960. * })
  8961. */
  8962. Engine.prototype.runRenderLoop = function (renderFunction) {
  8963. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8964. return;
  8965. }
  8966. this._activeRenderLoops.push(renderFunction);
  8967. if (!this._renderingQueueLaunched) {
  8968. this._renderingQueueLaunched = true;
  8969. this._bindedRenderFunction = this._renderLoop.bind(this);
  8970. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8971. }
  8972. };
  8973. /**
  8974. * Toggle full screen mode.
  8975. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8976. * @param {any} options - an options object to be sent to the requestFullscreen function
  8977. */
  8978. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8979. if (this.isFullscreen) {
  8980. BABYLON.Tools.ExitFullscreen();
  8981. }
  8982. else {
  8983. this._pointerLockRequested = requestPointerLock;
  8984. if (this._renderingCanvas) {
  8985. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8986. }
  8987. }
  8988. };
  8989. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8990. if (stencil === void 0) { stencil = false; }
  8991. this.applyStates();
  8992. var mode = 0;
  8993. if (backBuffer && color) {
  8994. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8995. mode |= this._gl.COLOR_BUFFER_BIT;
  8996. }
  8997. if (depth) {
  8998. this._gl.clearDepth(1.0);
  8999. mode |= this._gl.DEPTH_BUFFER_BIT;
  9000. }
  9001. if (stencil) {
  9002. this._gl.clearStencil(0);
  9003. mode |= this._gl.STENCIL_BUFFER_BIT;
  9004. }
  9005. this._gl.clear(mode);
  9006. };
  9007. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9008. var gl = this._gl;
  9009. // Save state
  9010. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9011. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9012. // Change state
  9013. gl.enable(gl.SCISSOR_TEST);
  9014. gl.scissor(x, y, width, height);
  9015. // Clear
  9016. this.clear(clearColor, true, true, true);
  9017. // Restore state
  9018. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9019. if (curScissor === true) {
  9020. gl.enable(gl.SCISSOR_TEST);
  9021. }
  9022. else {
  9023. gl.disable(gl.SCISSOR_TEST);
  9024. }
  9025. };
  9026. /**
  9027. * Set the WebGL's viewport
  9028. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9029. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9030. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9031. */
  9032. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9033. var width = requiredWidth || this.getRenderWidth();
  9034. var height = requiredHeight || this.getRenderHeight();
  9035. var x = viewport.x || 0;
  9036. var y = viewport.y || 0;
  9037. this._cachedViewport = viewport;
  9038. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9039. };
  9040. /**
  9041. * Directly set the WebGL Viewport
  9042. * The x, y, width & height are directly passed to the WebGL call
  9043. * @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.
  9044. */
  9045. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9046. var currentViewport = this._cachedViewport;
  9047. this._cachedViewport = null;
  9048. this._gl.viewport(x, y, width, height);
  9049. return currentViewport;
  9050. };
  9051. Engine.prototype.beginFrame = function () {
  9052. this.onBeginFrameObservable.notifyObservers(this);
  9053. this._measureFps();
  9054. };
  9055. Engine.prototype.endFrame = function () {
  9056. //force a flush in case we are using a bad OS.
  9057. if (this._badOS) {
  9058. this.flushFramebuffer();
  9059. }
  9060. //submit frame to the vr device, if enabled
  9061. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9062. // TODO: We should only submit the frame if we read frameData successfully.
  9063. this._vrDisplay.submitFrame();
  9064. }
  9065. this.onEndFrameObservable.notifyObservers(this);
  9066. };
  9067. /**
  9068. * resize the view according to the canvas' size.
  9069. * @example
  9070. * window.addEventListener("resize", function () {
  9071. * engine.resize();
  9072. * });
  9073. */
  9074. Engine.prototype.resize = function () {
  9075. // We're not resizing the size of the canvas while in VR mode & presenting
  9076. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9077. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9078. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9079. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9080. }
  9081. };
  9082. /**
  9083. * force a specific size of the canvas
  9084. * @param {number} width - the new canvas' width
  9085. * @param {number} height - the new canvas' height
  9086. */
  9087. Engine.prototype.setSize = function (width, height) {
  9088. if (!this._renderingCanvas) {
  9089. return;
  9090. }
  9091. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9092. return;
  9093. }
  9094. this._renderingCanvas.width = width;
  9095. this._renderingCanvas.height = height;
  9096. for (var index = 0; index < this.scenes.length; index++) {
  9097. var scene = this.scenes[index];
  9098. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9099. var cam = scene.cameras[camIndex];
  9100. cam._currentRenderId = 0;
  9101. }
  9102. }
  9103. if (this.onResizeObservable.hasObservers) {
  9104. this.onResizeObservable.notifyObservers(this);
  9105. }
  9106. };
  9107. // WebVR functions
  9108. Engine.prototype.isVRDevicePresent = function () {
  9109. return !!this._vrDisplay;
  9110. };
  9111. Engine.prototype.getVRDevice = function () {
  9112. return this._vrDisplay;
  9113. };
  9114. Engine.prototype.initWebVR = function () {
  9115. var _this = this;
  9116. var notifyObservers = function () {
  9117. var eventArgs = {
  9118. vrDisplay: _this._vrDisplay,
  9119. vrSupported: _this._vrSupported
  9120. };
  9121. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9122. };
  9123. if (!this._onVrDisplayConnect) {
  9124. this._onVrDisplayConnect = function (event) {
  9125. _this._vrDisplay = event.display;
  9126. notifyObservers();
  9127. };
  9128. this._onVrDisplayDisconnect = function () {
  9129. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9130. _this._vrDisplay = undefined;
  9131. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9132. notifyObservers();
  9133. };
  9134. this._onVrDisplayPresentChange = function () {
  9135. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9136. };
  9137. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9138. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9139. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9140. }
  9141. this._getVRDisplays(notifyObservers);
  9142. return this.onVRDisplayChangedObservable;
  9143. };
  9144. Engine.prototype.enableVR = function () {
  9145. var _this = this;
  9146. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9147. var onResolved = function () {
  9148. _this.onVRRequestPresentComplete.notifyObservers(true);
  9149. _this._onVRFullScreenTriggered();
  9150. };
  9151. var onRejected = function () {
  9152. _this.onVRRequestPresentComplete.notifyObservers(false);
  9153. };
  9154. this.onVRRequestPresentStart.notifyObservers(this);
  9155. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9156. }
  9157. };
  9158. Engine.prototype.disableVR = function () {
  9159. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9160. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9161. }
  9162. };
  9163. Engine.prototype._getVRDisplays = function (callback) {
  9164. var _this = this;
  9165. var getWebVRDevices = function (devices) {
  9166. _this._vrSupported = true;
  9167. // note that devices may actually be an empty array. This is fine;
  9168. // we expect this._vrDisplay to be undefined in this case.
  9169. return _this._vrDisplay = devices[0];
  9170. };
  9171. if (navigator.getVRDisplays) {
  9172. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9173. // TODO: System CANNOT support WebVR, despite API presence.
  9174. _this._vrSupported = false;
  9175. callback();
  9176. });
  9177. }
  9178. else {
  9179. // TODO: Browser does not support WebVR
  9180. this._vrDisplay = undefined;
  9181. this._vrSupported = false;
  9182. callback();
  9183. }
  9184. };
  9185. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9186. if (this._currentRenderTarget) {
  9187. this.unBindFramebuffer(this._currentRenderTarget);
  9188. }
  9189. this._currentRenderTarget = texture;
  9190. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9191. var gl = this._gl;
  9192. if (texture.isCube) {
  9193. if (faceIndex === undefined) {
  9194. faceIndex = 0;
  9195. }
  9196. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9197. }
  9198. if (this._cachedViewport && !forceFullscreenViewport) {
  9199. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9200. }
  9201. else {
  9202. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9203. }
  9204. this.wipeCaches();
  9205. };
  9206. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9207. if (this._currentFramebuffer !== framebuffer) {
  9208. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9209. this._currentFramebuffer = framebuffer;
  9210. }
  9211. };
  9212. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9213. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9214. this._currentRenderTarget = null;
  9215. // If MSAA, we need to bitblt back to main texture
  9216. var gl = this._gl;
  9217. if (texture._MSAAFramebuffer) {
  9218. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9219. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9220. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9221. }
  9222. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9223. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9224. gl.generateMipmap(gl.TEXTURE_2D);
  9225. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9226. }
  9227. if (onBeforeUnbind) {
  9228. if (texture._MSAAFramebuffer) {
  9229. // Bind the correct framebuffer
  9230. this.bindUnboundFramebuffer(texture._framebuffer);
  9231. }
  9232. onBeforeUnbind();
  9233. }
  9234. this.bindUnboundFramebuffer(null);
  9235. };
  9236. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9237. if (texture.generateMipMaps) {
  9238. var gl = this._gl;
  9239. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9240. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9241. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9242. }
  9243. };
  9244. Engine.prototype.flushFramebuffer = function () {
  9245. this._gl.flush();
  9246. };
  9247. Engine.prototype.restoreDefaultFramebuffer = function () {
  9248. if (this._currentRenderTarget) {
  9249. this.unBindFramebuffer(this._currentRenderTarget);
  9250. }
  9251. else {
  9252. this.bindUnboundFramebuffer(null);
  9253. }
  9254. if (this._cachedViewport) {
  9255. this.setViewport(this._cachedViewport);
  9256. }
  9257. this.wipeCaches();
  9258. };
  9259. // UBOs
  9260. Engine.prototype.createUniformBuffer = function (elements) {
  9261. var ubo = this._gl.createBuffer();
  9262. if (!ubo) {
  9263. throw new Error("Unable to create uniform buffer");
  9264. }
  9265. this.bindUniformBuffer(ubo);
  9266. if (elements instanceof Float32Array) {
  9267. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9268. }
  9269. else {
  9270. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9271. }
  9272. this.bindUniformBuffer(null);
  9273. ubo.references = 1;
  9274. return ubo;
  9275. };
  9276. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9277. var ubo = this._gl.createBuffer();
  9278. if (!ubo) {
  9279. throw new Error("Unable to create dynamic uniform buffer");
  9280. }
  9281. this.bindUniformBuffer(ubo);
  9282. if (elements instanceof Float32Array) {
  9283. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9284. }
  9285. else {
  9286. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9287. }
  9288. this.bindUniformBuffer(null);
  9289. ubo.references = 1;
  9290. return ubo;
  9291. };
  9292. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9293. this.bindUniformBuffer(uniformBuffer);
  9294. if (offset === undefined) {
  9295. offset = 0;
  9296. }
  9297. if (count === undefined) {
  9298. if (elements instanceof Float32Array) {
  9299. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9300. }
  9301. else {
  9302. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9303. }
  9304. }
  9305. else {
  9306. if (elements instanceof Float32Array) {
  9307. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9308. }
  9309. else {
  9310. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9311. }
  9312. }
  9313. this.bindUniformBuffer(null);
  9314. };
  9315. // VBOs
  9316. Engine.prototype._resetVertexBufferBinding = function () {
  9317. this.bindArrayBuffer(null);
  9318. this._cachedVertexBuffers = null;
  9319. };
  9320. Engine.prototype.createVertexBuffer = function (vertices) {
  9321. var vbo = this._gl.createBuffer();
  9322. if (!vbo) {
  9323. throw new Error("Unable to create vertex buffer");
  9324. }
  9325. this.bindArrayBuffer(vbo);
  9326. if (vertices instanceof Float32Array) {
  9327. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9328. }
  9329. else {
  9330. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9331. }
  9332. this._resetVertexBufferBinding();
  9333. vbo.references = 1;
  9334. return vbo;
  9335. };
  9336. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9337. var vbo = this._gl.createBuffer();
  9338. if (!vbo) {
  9339. throw new Error("Unable to create dynamic vertex buffer");
  9340. }
  9341. this.bindArrayBuffer(vbo);
  9342. if (vertices instanceof Float32Array) {
  9343. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9344. }
  9345. else {
  9346. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9347. }
  9348. this._resetVertexBufferBinding();
  9349. vbo.references = 1;
  9350. return vbo;
  9351. };
  9352. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9353. if (offset === void 0) { offset = 0; }
  9354. // Force cache update
  9355. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9356. this.bindIndexBuffer(indexBuffer);
  9357. var arrayBuffer;
  9358. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9359. arrayBuffer = indices;
  9360. }
  9361. else {
  9362. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9363. }
  9364. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9365. this._resetIndexBufferBinding();
  9366. };
  9367. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9368. this.bindArrayBuffer(vertexBuffer);
  9369. if (offset === undefined) {
  9370. offset = 0;
  9371. }
  9372. if (count === undefined) {
  9373. if (vertices instanceof Float32Array) {
  9374. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9375. }
  9376. else {
  9377. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9378. }
  9379. }
  9380. else {
  9381. if (vertices instanceof Float32Array) {
  9382. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9383. }
  9384. else {
  9385. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9386. }
  9387. }
  9388. this._resetVertexBufferBinding();
  9389. };
  9390. Engine.prototype._resetIndexBufferBinding = function () {
  9391. this.bindIndexBuffer(null);
  9392. this._cachedIndexBuffer = null;
  9393. };
  9394. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9395. var vbo = this._gl.createBuffer();
  9396. if (!vbo) {
  9397. throw new Error("Unable to create index buffer");
  9398. }
  9399. this.bindIndexBuffer(vbo);
  9400. // Check for 32 bits indices
  9401. var arrayBuffer;
  9402. var need32Bits = false;
  9403. if (indices instanceof Uint16Array) {
  9404. arrayBuffer = indices;
  9405. }
  9406. else {
  9407. //check 32 bit support
  9408. if (this._caps.uintIndices) {
  9409. if (indices instanceof Uint32Array) {
  9410. arrayBuffer = indices;
  9411. need32Bits = true;
  9412. }
  9413. else {
  9414. //number[] or Int32Array, check if 32 bit is necessary
  9415. for (var index = 0; index < indices.length; index++) {
  9416. if (indices[index] > 65535) {
  9417. need32Bits = true;
  9418. break;
  9419. }
  9420. }
  9421. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9422. }
  9423. }
  9424. else {
  9425. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9426. arrayBuffer = new Uint16Array(indices);
  9427. }
  9428. }
  9429. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9430. this._resetIndexBufferBinding();
  9431. vbo.references = 1;
  9432. vbo.is32Bits = need32Bits;
  9433. return vbo;
  9434. };
  9435. Engine.prototype.bindArrayBuffer = function (buffer) {
  9436. if (!this._vaoRecordInProgress) {
  9437. this._unbindVertexArrayObject();
  9438. }
  9439. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9440. };
  9441. Engine.prototype.bindUniformBuffer = function (buffer) {
  9442. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9443. };
  9444. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9445. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9446. };
  9447. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9448. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9449. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9450. };
  9451. ;
  9452. Engine.prototype.bindIndexBuffer = function (buffer) {
  9453. if (!this._vaoRecordInProgress) {
  9454. this._unbindVertexArrayObject();
  9455. }
  9456. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9457. };
  9458. Engine.prototype.bindBuffer = function (buffer, target) {
  9459. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9460. this._gl.bindBuffer(target, buffer);
  9461. this._currentBoundBuffer[target] = buffer;
  9462. }
  9463. };
  9464. Engine.prototype.updateArrayBuffer = function (data) {
  9465. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9466. };
  9467. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9468. var pointer = this._currentBufferPointers[indx];
  9469. var changed = false;
  9470. if (!pointer.active) {
  9471. changed = true;
  9472. pointer.active = true;
  9473. pointer.index = indx;
  9474. pointer.size = size;
  9475. pointer.type = type;
  9476. pointer.normalized = normalized;
  9477. pointer.stride = stride;
  9478. pointer.offset = offset;
  9479. pointer.buffer = buffer;
  9480. }
  9481. else {
  9482. if (pointer.buffer !== buffer) {
  9483. pointer.buffer = buffer;
  9484. changed = true;
  9485. }
  9486. if (pointer.size !== size) {
  9487. pointer.size = size;
  9488. changed = true;
  9489. }
  9490. if (pointer.type !== type) {
  9491. pointer.type = type;
  9492. changed = true;
  9493. }
  9494. if (pointer.normalized !== normalized) {
  9495. pointer.normalized = normalized;
  9496. changed = true;
  9497. }
  9498. if (pointer.stride !== stride) {
  9499. pointer.stride = stride;
  9500. changed = true;
  9501. }
  9502. if (pointer.offset !== offset) {
  9503. pointer.offset = offset;
  9504. changed = true;
  9505. }
  9506. }
  9507. if (changed || this._vaoRecordInProgress) {
  9508. this.bindArrayBuffer(buffer);
  9509. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9510. }
  9511. };
  9512. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9513. if (indexBuffer == null) {
  9514. return;
  9515. }
  9516. if (this._cachedIndexBuffer !== indexBuffer) {
  9517. this._cachedIndexBuffer = indexBuffer;
  9518. this.bindIndexBuffer(indexBuffer);
  9519. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9520. }
  9521. };
  9522. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9523. var attributes = effect.getAttributesNames();
  9524. if (!this._vaoRecordInProgress) {
  9525. this._unbindVertexArrayObject();
  9526. }
  9527. this.unbindAllAttributes();
  9528. for (var index = 0; index < attributes.length; index++) {
  9529. var order = effect.getAttributeLocation(index);
  9530. if (order >= 0) {
  9531. var vertexBuffer = vertexBuffers[attributes[index]];
  9532. if (!vertexBuffer) {
  9533. continue;
  9534. }
  9535. this._gl.enableVertexAttribArray(order);
  9536. if (!this._vaoRecordInProgress) {
  9537. this._vertexAttribArraysEnabled[order] = true;
  9538. }
  9539. var buffer = vertexBuffer.getBuffer();
  9540. if (buffer) {
  9541. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9542. if (vertexBuffer.getIsInstanced()) {
  9543. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9544. if (!this._vaoRecordInProgress) {
  9545. this._currentInstanceLocations.push(order);
  9546. this._currentInstanceBuffers.push(buffer);
  9547. }
  9548. }
  9549. }
  9550. }
  9551. }
  9552. };
  9553. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9554. var vao = this._gl.createVertexArray();
  9555. this._vaoRecordInProgress = true;
  9556. this._gl.bindVertexArray(vao);
  9557. this._mustWipeVertexAttributes = true;
  9558. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9559. this.bindIndexBuffer(indexBuffer);
  9560. this._vaoRecordInProgress = false;
  9561. this._gl.bindVertexArray(null);
  9562. return vao;
  9563. };
  9564. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9565. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9566. this._cachedVertexArrayObject = vertexArrayObject;
  9567. this._gl.bindVertexArray(vertexArrayObject);
  9568. this._cachedVertexBuffers = null;
  9569. this._cachedIndexBuffer = null;
  9570. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9571. this._mustWipeVertexAttributes = true;
  9572. }
  9573. };
  9574. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9575. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9576. this._cachedVertexBuffers = vertexBuffer;
  9577. this._cachedEffectForVertexBuffers = effect;
  9578. var attributesCount = effect.getAttributesCount();
  9579. this._unbindVertexArrayObject();
  9580. this.unbindAllAttributes();
  9581. var offset = 0;
  9582. for (var index = 0; index < attributesCount; index++) {
  9583. if (index < vertexDeclaration.length) {
  9584. var order = effect.getAttributeLocation(index);
  9585. if (order >= 0) {
  9586. this._gl.enableVertexAttribArray(order);
  9587. this._vertexAttribArraysEnabled[order] = true;
  9588. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9589. }
  9590. offset += vertexDeclaration[index] * 4;
  9591. }
  9592. }
  9593. }
  9594. this._bindIndexBufferWithCache(indexBuffer);
  9595. };
  9596. Engine.prototype._unbindVertexArrayObject = function () {
  9597. if (!this._cachedVertexArrayObject) {
  9598. return;
  9599. }
  9600. this._cachedVertexArrayObject = null;
  9601. this._gl.bindVertexArray(null);
  9602. };
  9603. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9604. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9605. this._cachedVertexBuffers = vertexBuffers;
  9606. this._cachedEffectForVertexBuffers = effect;
  9607. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9608. }
  9609. this._bindIndexBufferWithCache(indexBuffer);
  9610. };
  9611. Engine.prototype.unbindInstanceAttributes = function () {
  9612. var boundBuffer;
  9613. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9614. var instancesBuffer = this._currentInstanceBuffers[i];
  9615. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9616. boundBuffer = instancesBuffer;
  9617. this.bindArrayBuffer(instancesBuffer);
  9618. }
  9619. var offsetLocation = this._currentInstanceLocations[i];
  9620. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9621. }
  9622. this._currentInstanceBuffers.length = 0;
  9623. this._currentInstanceLocations.length = 0;
  9624. };
  9625. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9626. this._gl.deleteVertexArray(vao);
  9627. };
  9628. Engine.prototype._releaseBuffer = function (buffer) {
  9629. buffer.references--;
  9630. if (buffer.references === 0) {
  9631. this._gl.deleteBuffer(buffer);
  9632. return true;
  9633. }
  9634. return false;
  9635. };
  9636. Engine.prototype.createInstancesBuffer = function (capacity) {
  9637. var buffer = this._gl.createBuffer();
  9638. if (!buffer) {
  9639. throw new Error("Unable to create instance buffer");
  9640. }
  9641. buffer.capacity = capacity;
  9642. this.bindArrayBuffer(buffer);
  9643. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9644. return buffer;
  9645. };
  9646. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9647. this._gl.deleteBuffer(buffer);
  9648. };
  9649. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9650. this.bindArrayBuffer(instancesBuffer);
  9651. if (data) {
  9652. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9653. }
  9654. if (offsetLocations[0].index !== undefined) {
  9655. var stride = 0;
  9656. for (var i = 0; i < offsetLocations.length; i++) {
  9657. var ai = offsetLocations[i];
  9658. stride += ai.attributeSize * 4;
  9659. }
  9660. for (var i = 0; i < offsetLocations.length; i++) {
  9661. var ai = offsetLocations[i];
  9662. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9663. this._gl.enableVertexAttribArray(ai.index);
  9664. this._vertexAttribArraysEnabled[ai.index] = true;
  9665. }
  9666. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9667. this._gl.vertexAttribDivisor(ai.index, 1);
  9668. this._currentInstanceLocations.push(ai.index);
  9669. this._currentInstanceBuffers.push(instancesBuffer);
  9670. }
  9671. }
  9672. else {
  9673. for (var index = 0; index < 4; index++) {
  9674. var offsetLocation = offsetLocations[index];
  9675. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9676. this._gl.enableVertexAttribArray(offsetLocation);
  9677. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9678. }
  9679. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9680. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9681. this._currentInstanceLocations.push(offsetLocation);
  9682. this._currentInstanceBuffers.push(instancesBuffer);
  9683. }
  9684. }
  9685. };
  9686. Engine.prototype.applyStates = function () {
  9687. this._depthCullingState.apply(this._gl);
  9688. this._stencilState.apply(this._gl);
  9689. this._alphaState.apply(this._gl);
  9690. };
  9691. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9692. // Apply states
  9693. this.applyStates();
  9694. this._drawCalls.addCount(1, false);
  9695. // Render
  9696. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9697. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9698. if (instancesCount) {
  9699. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9700. return;
  9701. }
  9702. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9703. };
  9704. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9705. // Apply states
  9706. this.applyStates();
  9707. this._drawCalls.addCount(1, false);
  9708. if (instancesCount) {
  9709. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9710. return;
  9711. }
  9712. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9713. };
  9714. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9715. // Apply states
  9716. this.applyStates();
  9717. this._drawCalls.addCount(1, false);
  9718. if (instancesCount) {
  9719. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9720. return;
  9721. }
  9722. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9723. };
  9724. // Shaders
  9725. Engine.prototype._releaseEffect = function (effect) {
  9726. if (this._compiledEffects[effect._key]) {
  9727. delete this._compiledEffects[effect._key];
  9728. this._deleteProgram(effect.getProgram());
  9729. }
  9730. };
  9731. Engine.prototype._deleteProgram = function (program) {
  9732. if (program) {
  9733. program.__SPECTOR_rebuildProgram = null;
  9734. if (program.transformFeedback) {
  9735. this.deleteTransformFeedback(program.transformFeedback);
  9736. program.transformFeedback = null;
  9737. }
  9738. this._gl.deleteProgram(program);
  9739. }
  9740. };
  9741. /**
  9742. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9743. * @param samplers An array of string used to represent textures
  9744. */
  9745. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9746. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9747. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9748. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9749. if (this._compiledEffects[name]) {
  9750. var compiledEffect = this._compiledEffects[name];
  9751. if (onCompiled && compiledEffect.isReady()) {
  9752. onCompiled(compiledEffect);
  9753. }
  9754. return compiledEffect;
  9755. }
  9756. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9757. effect._key = name;
  9758. this._compiledEffects[name] = effect;
  9759. return effect;
  9760. };
  9761. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9762. if (uniformsNames === void 0) { uniformsNames = []; }
  9763. if (samplers === void 0) { samplers = []; }
  9764. if (defines === void 0) { defines = ""; }
  9765. return this.createEffect({
  9766. vertex: "particles",
  9767. fragmentElement: fragmentName
  9768. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9769. };
  9770. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9771. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9772. context = context || this._gl;
  9773. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9774. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9775. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9776. };
  9777. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9778. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9779. context = context || this._gl;
  9780. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9781. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9782. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9783. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9784. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9785. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9786. return program;
  9787. };
  9788. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  9789. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9790. var shaderProgram = context.createProgram();
  9791. if (!shaderProgram) {
  9792. throw new Error("Unable to create program");
  9793. }
  9794. context.attachShader(shaderProgram, vertexShader);
  9795. context.attachShader(shaderProgram, fragmentShader);
  9796. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9797. var transformFeedback = this.createTransformFeedback();
  9798. this.bindTransformFeedback(transformFeedback);
  9799. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  9800. shaderProgram.transformFeedback = transformFeedback;
  9801. }
  9802. context.linkProgram(shaderProgram);
  9803. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9804. this.bindTransformFeedback(null);
  9805. }
  9806. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9807. if (!linked) {
  9808. context.validateProgram(shaderProgram);
  9809. var error = context.getProgramInfoLog(shaderProgram);
  9810. if (error) {
  9811. throw new Error(error);
  9812. }
  9813. }
  9814. context.deleteShader(vertexShader);
  9815. context.deleteShader(fragmentShader);
  9816. return shaderProgram;
  9817. };
  9818. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9819. var results = new Array();
  9820. for (var index = 0; index < uniformsNames.length; index++) {
  9821. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9822. }
  9823. return results;
  9824. };
  9825. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9826. var results = [];
  9827. for (var index = 0; index < attributesNames.length; index++) {
  9828. try {
  9829. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9830. }
  9831. catch (e) {
  9832. results.push(-1);
  9833. }
  9834. }
  9835. return results;
  9836. };
  9837. Engine.prototype.enableEffect = function (effect) {
  9838. if (!effect) {
  9839. return;
  9840. }
  9841. // Use program
  9842. this.setProgram(effect.getProgram());
  9843. this._currentEffect = effect;
  9844. if (effect.onBind) {
  9845. effect.onBind(effect);
  9846. }
  9847. effect.onBindObservable.notifyObservers(effect);
  9848. };
  9849. Engine.prototype.setIntArray = function (uniform, array) {
  9850. if (!uniform)
  9851. return;
  9852. this._gl.uniform1iv(uniform, array);
  9853. };
  9854. Engine.prototype.setIntArray2 = function (uniform, array) {
  9855. if (!uniform || array.length % 2 !== 0)
  9856. return;
  9857. this._gl.uniform2iv(uniform, array);
  9858. };
  9859. Engine.prototype.setIntArray3 = function (uniform, array) {
  9860. if (!uniform || array.length % 3 !== 0)
  9861. return;
  9862. this._gl.uniform3iv(uniform, array);
  9863. };
  9864. Engine.prototype.setIntArray4 = function (uniform, array) {
  9865. if (!uniform || array.length % 4 !== 0)
  9866. return;
  9867. this._gl.uniform4iv(uniform, array);
  9868. };
  9869. Engine.prototype.setFloatArray = function (uniform, array) {
  9870. if (!uniform)
  9871. return;
  9872. this._gl.uniform1fv(uniform, array);
  9873. };
  9874. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9875. if (!uniform || array.length % 2 !== 0)
  9876. return;
  9877. this._gl.uniform2fv(uniform, array);
  9878. };
  9879. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9880. if (!uniform || array.length % 3 !== 0)
  9881. return;
  9882. this._gl.uniform3fv(uniform, array);
  9883. };
  9884. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9885. if (!uniform || array.length % 4 !== 0)
  9886. return;
  9887. this._gl.uniform4fv(uniform, array);
  9888. };
  9889. Engine.prototype.setArray = function (uniform, array) {
  9890. if (!uniform)
  9891. return;
  9892. this._gl.uniform1fv(uniform, array);
  9893. };
  9894. Engine.prototype.setArray2 = function (uniform, array) {
  9895. if (!uniform || array.length % 2 !== 0)
  9896. return;
  9897. this._gl.uniform2fv(uniform, array);
  9898. };
  9899. Engine.prototype.setArray3 = function (uniform, array) {
  9900. if (!uniform || array.length % 3 !== 0)
  9901. return;
  9902. this._gl.uniform3fv(uniform, array);
  9903. };
  9904. Engine.prototype.setArray4 = function (uniform, array) {
  9905. if (!uniform || array.length % 4 !== 0)
  9906. return;
  9907. this._gl.uniform4fv(uniform, array);
  9908. };
  9909. Engine.prototype.setMatrices = function (uniform, matrices) {
  9910. if (!uniform)
  9911. return;
  9912. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9913. };
  9914. Engine.prototype.setMatrix = function (uniform, matrix) {
  9915. if (!uniform)
  9916. return;
  9917. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9918. };
  9919. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9920. if (!uniform)
  9921. return;
  9922. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9923. };
  9924. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9925. if (!uniform)
  9926. return;
  9927. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9928. };
  9929. Engine.prototype.setFloat = function (uniform, value) {
  9930. if (!uniform)
  9931. return;
  9932. this._gl.uniform1f(uniform, value);
  9933. };
  9934. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9935. if (!uniform)
  9936. return;
  9937. this._gl.uniform2f(uniform, x, y);
  9938. };
  9939. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9940. if (!uniform)
  9941. return;
  9942. this._gl.uniform3f(uniform, x, y, z);
  9943. };
  9944. Engine.prototype.setBool = function (uniform, bool) {
  9945. if (!uniform)
  9946. return;
  9947. this._gl.uniform1i(uniform, bool);
  9948. };
  9949. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9950. if (!uniform)
  9951. return;
  9952. this._gl.uniform4f(uniform, x, y, z, w);
  9953. };
  9954. Engine.prototype.setColor3 = function (uniform, color3) {
  9955. if (!uniform)
  9956. return;
  9957. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9958. };
  9959. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9960. if (!uniform)
  9961. return;
  9962. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9963. };
  9964. // States
  9965. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9966. if (zOffset === void 0) { zOffset = 0; }
  9967. if (reverseSide === void 0) { reverseSide = false; }
  9968. // Culling
  9969. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9970. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9971. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9972. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9973. if (culling) {
  9974. this._depthCullingState.cullFace = cullFace;
  9975. this._depthCullingState.cull = true;
  9976. }
  9977. else {
  9978. this._depthCullingState.cull = false;
  9979. }
  9980. }
  9981. // Z offset
  9982. this.setZOffset(zOffset);
  9983. };
  9984. Engine.prototype.setZOffset = function (value) {
  9985. this._depthCullingState.zOffset = value;
  9986. };
  9987. Engine.prototype.getZOffset = function () {
  9988. return this._depthCullingState.zOffset;
  9989. };
  9990. Engine.prototype.setDepthBuffer = function (enable) {
  9991. this._depthCullingState.depthTest = enable;
  9992. };
  9993. Engine.prototype.getDepthWrite = function () {
  9994. return this._depthCullingState.depthMask;
  9995. };
  9996. Engine.prototype.setDepthWrite = function (enable) {
  9997. this._depthCullingState.depthMask = enable;
  9998. };
  9999. Engine.prototype.setColorWrite = function (enable) {
  10000. this._gl.colorMask(enable, enable, enable, enable);
  10001. this._colorWrite = enable;
  10002. };
  10003. Engine.prototype.getColorWrite = function () {
  10004. return this._colorWrite;
  10005. };
  10006. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10007. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10008. };
  10009. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10010. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10011. if (this._alphaMode === mode) {
  10012. return;
  10013. }
  10014. switch (mode) {
  10015. case Engine.ALPHA_DISABLE:
  10016. this._alphaState.alphaBlend = false;
  10017. break;
  10018. case Engine.ALPHA_PREMULTIPLIED:
  10019. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10020. this._alphaState.alphaBlend = true;
  10021. break;
  10022. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10023. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10024. this._alphaState.alphaBlend = true;
  10025. break;
  10026. case Engine.ALPHA_COMBINE:
  10027. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10028. this._alphaState.alphaBlend = true;
  10029. break;
  10030. case Engine.ALPHA_ONEONE:
  10031. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10032. this._alphaState.alphaBlend = true;
  10033. break;
  10034. case Engine.ALPHA_ADD:
  10035. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10036. this._alphaState.alphaBlend = true;
  10037. break;
  10038. case Engine.ALPHA_SUBTRACT:
  10039. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10040. this._alphaState.alphaBlend = true;
  10041. break;
  10042. case Engine.ALPHA_MULTIPLY:
  10043. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10044. this._alphaState.alphaBlend = true;
  10045. break;
  10046. case Engine.ALPHA_MAXIMIZED:
  10047. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10048. this._alphaState.alphaBlend = true;
  10049. break;
  10050. case Engine.ALPHA_INTERPOLATE:
  10051. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10052. this._alphaState.alphaBlend = true;
  10053. break;
  10054. case Engine.ALPHA_SCREENMODE:
  10055. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10056. this._alphaState.alphaBlend = true;
  10057. break;
  10058. }
  10059. if (!noDepthWriteChange) {
  10060. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10061. }
  10062. this._alphaMode = mode;
  10063. };
  10064. Engine.prototype.getAlphaMode = function () {
  10065. return this._alphaMode;
  10066. };
  10067. Engine.prototype.setAlphaTesting = function (enable) {
  10068. this._alphaTest = enable;
  10069. };
  10070. Engine.prototype.getAlphaTesting = function () {
  10071. return !!this._alphaTest;
  10072. };
  10073. // Textures
  10074. Engine.prototype.wipeCaches = function (bruteForce) {
  10075. if (this.preventCacheWipeBetweenFrames) {
  10076. return;
  10077. }
  10078. this.resetTextureCache();
  10079. this._currentEffect = null;
  10080. // 6/8/2017: deltakosh: Should not be required anymore.
  10081. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10082. if (bruteForce) {
  10083. this._currentProgram = null;
  10084. this._stencilState.reset();
  10085. this._depthCullingState.reset();
  10086. this.setDepthFunctionToLessOrEqual();
  10087. this._alphaState.reset();
  10088. }
  10089. this._cachedVertexBuffers = null;
  10090. this._cachedIndexBuffer = null;
  10091. this._cachedEffectForVertexBuffers = null;
  10092. this._unbindVertexArrayObject();
  10093. this.bindIndexBuffer(null);
  10094. this.bindArrayBuffer(null);
  10095. };
  10096. /**
  10097. * Set the compressed texture format to use, based on the formats you have, and the formats
  10098. * supported by the hardware / browser.
  10099. *
  10100. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10101. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10102. * to API arguments needed to compressed textures. This puts the burden on the container
  10103. * generator to house the arcane code for determining these for current & future formats.
  10104. *
  10105. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10106. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10107. *
  10108. * Note: The result of this call is not taken into account when a texture is base64.
  10109. *
  10110. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10111. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10112. *
  10113. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10114. * @returns The extension selected.
  10115. */
  10116. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10117. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10118. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10119. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10120. return this._textureFormatInUse = this._texturesSupported[i];
  10121. }
  10122. }
  10123. }
  10124. // actively set format to nothing, to allow this to be called more than once
  10125. // and possibly fail the 2nd time
  10126. this._textureFormatInUse = null;
  10127. return null;
  10128. };
  10129. Engine.prototype._createTexture = function () {
  10130. var texture = this._gl.createTexture();
  10131. if (!texture) {
  10132. throw new Error("Unable to create texture");
  10133. }
  10134. return texture;
  10135. };
  10136. /**
  10137. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10138. * @param {string} urlArg- This contains one of the following:
  10139. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10140. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10141. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10142. *
  10143. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10144. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10145. * @param {Scene} scene- Needed for loading to the correct scene.
  10146. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10147. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10148. * @param {callback} onError- Optional callback to be called upon failure.
  10149. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10150. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10151. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10152. *
  10153. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10154. */
  10155. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10156. var _this = this;
  10157. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10158. if (onLoad === void 0) { onLoad = null; }
  10159. if (onError === void 0) { onError = null; }
  10160. if (buffer === void 0) { buffer = null; }
  10161. if (fallBack === void 0) { fallBack = null; }
  10162. if (format === void 0) { format = null; }
  10163. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10164. var fromData = url.substr(0, 5) === "data:";
  10165. var fromBlob = url.substr(0, 5) === "blob:";
  10166. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10167. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10168. // establish the file extension, if possible
  10169. var lastDot = url.lastIndexOf('.');
  10170. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10171. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10172. var isTGA = (extension === ".tga");
  10173. // determine if a ktx file should be substituted
  10174. var isKTX = false;
  10175. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10176. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10177. isKTX = true;
  10178. }
  10179. if (scene) {
  10180. scene._addPendingData(texture);
  10181. }
  10182. texture.url = url;
  10183. texture.generateMipMaps = !noMipmap;
  10184. texture.samplingMode = samplingMode;
  10185. texture.invertY = invertY;
  10186. if (!this._doNotHandleContextLost) {
  10187. // Keep a link to the buffer only if we plan to handle context lost
  10188. texture._buffer = buffer;
  10189. }
  10190. if (onLoad) {
  10191. texture.onLoadedObservable.add(onLoad);
  10192. }
  10193. if (!fallBack)
  10194. this._internalTexturesCache.push(texture);
  10195. var onerror = function () {
  10196. if (scene) {
  10197. scene._removePendingData(texture);
  10198. }
  10199. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10200. if (isKTX) {
  10201. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10202. }
  10203. else if ((isTGA || isDDS) && BABYLON.Tools.UseFallbackTexture) {
  10204. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10205. }
  10206. else if (onError) {
  10207. onError();
  10208. }
  10209. };
  10210. var callback = null;
  10211. // processing for non-image formats
  10212. if (isKTX || isTGA || isDDS) {
  10213. if (isKTX) {
  10214. callback = function (data) {
  10215. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10216. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10217. ktx.uploadLevels(_this._gl, !noMipmap);
  10218. return false;
  10219. }, samplingMode);
  10220. };
  10221. }
  10222. else if (isTGA) {
  10223. callback = function (arrayBuffer) {
  10224. var data = new Uint8Array(arrayBuffer);
  10225. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10226. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10227. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10228. return false;
  10229. }, samplingMode);
  10230. };
  10231. }
  10232. else if (isDDS) {
  10233. callback = function (data) {
  10234. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10235. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10236. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10237. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10238. return false;
  10239. }, samplingMode);
  10240. };
  10241. }
  10242. if (!buffer) {
  10243. BABYLON.Tools.LoadFile(url, function (data) {
  10244. if (callback) {
  10245. callback(data);
  10246. }
  10247. }, undefined, scene ? scene.database : undefined, true, onerror);
  10248. }
  10249. else {
  10250. if (callback) {
  10251. callback(buffer);
  10252. }
  10253. }
  10254. // image format processing
  10255. }
  10256. else {
  10257. var onload = function (img) {
  10258. if (fromBlob && !_this._doNotHandleContextLost) {
  10259. // We need to store the image if we need to rebuild the texture
  10260. // in case of a webgl context lost
  10261. texture._buffer = img;
  10262. }
  10263. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10264. var gl = _this._gl;
  10265. var isPot = (img.width === potWidth && img.height === potHeight);
  10266. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10267. if (isPot) {
  10268. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10269. return false;
  10270. }
  10271. // Using shaders to rescale because canvas.drawImage is lossy
  10272. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10273. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10274. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10275. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10276. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10277. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10278. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10279. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10280. _this._releaseTexture(source);
  10281. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10282. continuationCallback();
  10283. });
  10284. return true;
  10285. }, samplingMode);
  10286. };
  10287. if (!fromData || isBase64)
  10288. if (buffer instanceof HTMLImageElement) {
  10289. onload(buffer);
  10290. }
  10291. else {
  10292. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10293. }
  10294. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10295. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10296. else
  10297. onload(buffer);
  10298. }
  10299. return texture;
  10300. };
  10301. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10302. var _this = this;
  10303. var rtt = this.createRenderTargetTexture({
  10304. width: destination.width,
  10305. height: destination.height,
  10306. }, {
  10307. generateMipMaps: false,
  10308. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10309. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10310. generateDepthBuffer: false,
  10311. generateStencilBuffer: false
  10312. });
  10313. if (!this._rescalePostProcess) {
  10314. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10315. }
  10316. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10317. _this._rescalePostProcess.onApply = function (effect) {
  10318. effect._bindTexture("textureSampler", source);
  10319. };
  10320. var hostingScene = scene;
  10321. if (!hostingScene) {
  10322. hostingScene = _this.scenes[_this.scenes.length - 1];
  10323. }
  10324. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10325. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10326. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10327. _this.unBindFramebuffer(rtt);
  10328. _this._releaseTexture(rtt);
  10329. if (onComplete) {
  10330. onComplete();
  10331. }
  10332. });
  10333. };
  10334. Engine.prototype._getInternalFormat = function (format) {
  10335. var internalFormat = this._gl.RGBA;
  10336. switch (format) {
  10337. case Engine.TEXTUREFORMAT_ALPHA:
  10338. internalFormat = this._gl.ALPHA;
  10339. break;
  10340. case Engine.TEXTUREFORMAT_LUMINANCE:
  10341. internalFormat = this._gl.LUMINANCE;
  10342. break;
  10343. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10344. internalFormat = this._gl.LUMINANCE_ALPHA;
  10345. break;
  10346. case Engine.TEXTUREFORMAT_RGB:
  10347. internalFormat = this._gl.RGB;
  10348. break;
  10349. case Engine.TEXTUREFORMAT_RGBA:
  10350. internalFormat = this._gl.RGBA;
  10351. break;
  10352. }
  10353. return internalFormat;
  10354. };
  10355. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10356. if (compression === void 0) { compression = null; }
  10357. if (!texture) {
  10358. return;
  10359. }
  10360. var internalFormat = this._getInternalFormat(format);
  10361. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10362. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10363. if (!this._doNotHandleContextLost) {
  10364. texture._bufferView = data;
  10365. texture.format = format;
  10366. texture.invertY = invertY;
  10367. texture._compression = compression;
  10368. }
  10369. if (texture.width % 4 !== 0) {
  10370. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10371. }
  10372. if (compression && data) {
  10373. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10374. }
  10375. else {
  10376. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10377. }
  10378. if (texture.generateMipMaps) {
  10379. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10380. }
  10381. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10382. this.resetTextureCache();
  10383. texture.isReady = true;
  10384. };
  10385. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10386. if (compression === void 0) { compression = null; }
  10387. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10388. texture.baseWidth = width;
  10389. texture.baseHeight = height;
  10390. texture.width = width;
  10391. texture.height = height;
  10392. texture.format = format;
  10393. texture.generateMipMaps = generateMipMaps;
  10394. texture.samplingMode = samplingMode;
  10395. texture.invertY = invertY;
  10396. texture._compression = compression;
  10397. if (!this._doNotHandleContextLost) {
  10398. texture._bufferView = data;
  10399. }
  10400. this.updateRawTexture(texture, data, format, invertY, compression);
  10401. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10402. // Filters
  10403. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10404. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10405. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10406. if (generateMipMaps) {
  10407. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10408. }
  10409. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10410. this._internalTexturesCache.push(texture);
  10411. return texture;
  10412. };
  10413. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10414. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10415. texture.baseWidth = width;
  10416. texture.baseHeight = height;
  10417. if (generateMipMaps) {
  10418. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10419. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10420. }
  10421. this.resetTextureCache();
  10422. texture.width = width;
  10423. texture.height = height;
  10424. texture.isReady = false;
  10425. texture.generateMipMaps = generateMipMaps;
  10426. texture.samplingMode = samplingMode;
  10427. this.updateTextureSamplingMode(samplingMode, texture);
  10428. this._internalTexturesCache.push(texture);
  10429. return texture;
  10430. };
  10431. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10432. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10433. if (texture.isCube) {
  10434. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10435. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10436. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10437. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10438. }
  10439. else if (texture.is3D) {
  10440. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10441. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10442. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10443. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10444. }
  10445. else {
  10446. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10447. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10448. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10449. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10450. }
  10451. texture.samplingMode = samplingMode;
  10452. };
  10453. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10454. if (premulAlpha === void 0) { premulAlpha = false; }
  10455. if (!texture) {
  10456. return;
  10457. }
  10458. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10459. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10460. if (premulAlpha) {
  10461. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10462. }
  10463. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10464. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10465. if (texture.generateMipMaps) {
  10466. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10467. }
  10468. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10469. if (premulAlpha) {
  10470. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10471. }
  10472. this.resetTextureCache();
  10473. texture.isReady = true;
  10474. };
  10475. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10476. if (!texture || texture._isDisabled) {
  10477. return;
  10478. }
  10479. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10480. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10481. try {
  10482. // Testing video texture support
  10483. if (this._videoTextureSupported === undefined) {
  10484. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10485. if (this._gl.getError() !== 0) {
  10486. this._videoTextureSupported = false;
  10487. }
  10488. else {
  10489. this._videoTextureSupported = true;
  10490. }
  10491. }
  10492. // Copy video through the current working canvas if video texture is not supported
  10493. if (!this._videoTextureSupported) {
  10494. if (!texture._workingCanvas) {
  10495. texture._workingCanvas = document.createElement("canvas");
  10496. var context = texture._workingCanvas.getContext("2d");
  10497. if (!context) {
  10498. throw new Error("Unable to get 2d context");
  10499. }
  10500. texture._workingContext = context;
  10501. texture._workingCanvas.width = texture.width;
  10502. texture._workingCanvas.height = texture.height;
  10503. }
  10504. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10505. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10506. }
  10507. else {
  10508. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10509. }
  10510. if (texture.generateMipMaps) {
  10511. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10512. }
  10513. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10514. this.resetTextureCache();
  10515. texture.isReady = true;
  10516. }
  10517. catch (ex) {
  10518. // Something unexpected
  10519. // Let's disable the texture
  10520. texture._isDisabled = true;
  10521. }
  10522. };
  10523. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10524. var fullOptions = new RenderTargetCreationOptions();
  10525. if (options !== undefined && typeof options === "object") {
  10526. fullOptions.generateMipMaps = options.generateMipMaps;
  10527. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10528. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10529. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10530. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10531. }
  10532. else {
  10533. fullOptions.generateMipMaps = options;
  10534. fullOptions.generateDepthBuffer = true;
  10535. fullOptions.generateStencilBuffer = false;
  10536. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10537. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10538. }
  10539. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10540. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10541. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10542. }
  10543. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10544. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10545. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10546. }
  10547. var gl = this._gl;
  10548. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10549. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10550. var width = size.width || size;
  10551. var height = size.height || size;
  10552. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10553. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10554. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10555. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10556. }
  10557. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10558. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10559. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10560. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10561. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10562. // Create the framebuffer
  10563. var framebuffer = gl.createFramebuffer();
  10564. this.bindUnboundFramebuffer(framebuffer);
  10565. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10566. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10567. if (fullOptions.generateMipMaps) {
  10568. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10569. }
  10570. // Unbind
  10571. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10572. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10573. this.bindUnboundFramebuffer(null);
  10574. texture._framebuffer = framebuffer;
  10575. texture.baseWidth = width;
  10576. texture.baseHeight = height;
  10577. texture.width = width;
  10578. texture.height = height;
  10579. texture.isReady = true;
  10580. texture.samples = 1;
  10581. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10582. texture.samplingMode = fullOptions.samplingMode;
  10583. texture.type = fullOptions.type;
  10584. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10585. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10586. this.resetTextureCache();
  10587. this._internalTexturesCache.push(texture);
  10588. return texture;
  10589. };
  10590. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10591. var generateMipMaps = false;
  10592. var generateDepthBuffer = true;
  10593. var generateStencilBuffer = false;
  10594. var generateDepthTexture = false;
  10595. var textureCount = 1;
  10596. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10597. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10598. var types = [], samplingModes = [];
  10599. if (options !== undefined) {
  10600. generateMipMaps = options.generateMipMaps;
  10601. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10602. generateStencilBuffer = options.generateStencilBuffer;
  10603. generateDepthTexture = options.generateDepthTexture;
  10604. textureCount = options.textureCount || 1;
  10605. if (options.types) {
  10606. types = options.types;
  10607. }
  10608. if (options.samplingModes) {
  10609. samplingModes = options.samplingModes;
  10610. }
  10611. }
  10612. var gl = this._gl;
  10613. // Create the framebuffer
  10614. var framebuffer = gl.createFramebuffer();
  10615. this.bindUnboundFramebuffer(framebuffer);
  10616. var width = size.width || size;
  10617. var height = size.height || size;
  10618. var textures = [];
  10619. var attachments = [];
  10620. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10621. for (var i = 0; i < textureCount; i++) {
  10622. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10623. var type = types[i] || defaultType;
  10624. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10625. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10626. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10627. }
  10628. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10629. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10630. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10631. }
  10632. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10633. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10634. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10635. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10636. }
  10637. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10638. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10639. textures.push(texture);
  10640. attachments.push(attachment);
  10641. gl.activeTexture(gl["TEXTURE" + i]);
  10642. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10643. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10644. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10647. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10648. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10649. if (generateMipMaps) {
  10650. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10651. }
  10652. // Unbind
  10653. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10654. texture._framebuffer = framebuffer;
  10655. texture._depthStencilBuffer = depthStencilBuffer;
  10656. texture.baseWidth = width;
  10657. texture.baseHeight = height;
  10658. texture.width = width;
  10659. texture.height = height;
  10660. texture.isReady = true;
  10661. texture.samples = 1;
  10662. texture.generateMipMaps = generateMipMaps;
  10663. texture.samplingMode = samplingMode;
  10664. texture.type = type;
  10665. texture._generateDepthBuffer = generateDepthBuffer;
  10666. texture._generateStencilBuffer = generateStencilBuffer;
  10667. this._internalTexturesCache.push(texture);
  10668. }
  10669. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10670. // Depth texture
  10671. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10672. gl.activeTexture(gl.TEXTURE0);
  10673. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10674. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10675. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10676. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10677. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10678. 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);
  10679. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10680. depthTexture._framebuffer = framebuffer;
  10681. depthTexture.baseWidth = width;
  10682. depthTexture.baseHeight = height;
  10683. depthTexture.width = width;
  10684. depthTexture.height = height;
  10685. depthTexture.isReady = true;
  10686. depthTexture.samples = 1;
  10687. depthTexture.generateMipMaps = generateMipMaps;
  10688. depthTexture.samplingMode = gl.NEAREST;
  10689. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10690. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10691. textures.push(depthTexture);
  10692. this._internalTexturesCache.push(depthTexture);
  10693. }
  10694. gl.drawBuffers(attachments);
  10695. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10696. this.bindUnboundFramebuffer(null);
  10697. this.resetTextureCache();
  10698. return textures;
  10699. };
  10700. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10701. if (samples === void 0) { samples = 1; }
  10702. var depthStencilBuffer = null;
  10703. var gl = this._gl;
  10704. // Create the depth/stencil buffer
  10705. if (generateStencilBuffer) {
  10706. depthStencilBuffer = gl.createRenderbuffer();
  10707. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10708. if (samples > 1) {
  10709. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10710. }
  10711. else {
  10712. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10713. }
  10714. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10715. }
  10716. else if (generateDepthBuffer) {
  10717. depthStencilBuffer = gl.createRenderbuffer();
  10718. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10719. if (samples > 1) {
  10720. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10721. }
  10722. else {
  10723. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10724. }
  10725. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10726. }
  10727. return depthStencilBuffer;
  10728. };
  10729. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10730. if (this.webGLVersion < 2 || !texture) {
  10731. return 1;
  10732. }
  10733. if (texture.samples === samples) {
  10734. return samples;
  10735. }
  10736. var gl = this._gl;
  10737. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10738. // Dispose previous render buffers
  10739. if (texture._depthStencilBuffer) {
  10740. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10741. }
  10742. if (texture._MSAAFramebuffer) {
  10743. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10744. }
  10745. if (texture._MSAARenderBuffer) {
  10746. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10747. }
  10748. if (samples > 1) {
  10749. var framebuffer = gl.createFramebuffer();
  10750. if (!framebuffer) {
  10751. throw new Error("Unable to create multi sampled framebuffer");
  10752. }
  10753. texture._MSAAFramebuffer = framebuffer;
  10754. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10755. var colorRenderbuffer = gl.createRenderbuffer();
  10756. if (!colorRenderbuffer) {
  10757. throw new Error("Unable to create multi sampled framebuffer");
  10758. }
  10759. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10760. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10761. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10762. texture._MSAARenderBuffer = colorRenderbuffer;
  10763. }
  10764. else {
  10765. this.bindUnboundFramebuffer(texture._framebuffer);
  10766. }
  10767. texture.samples = samples;
  10768. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10769. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10770. this.bindUnboundFramebuffer(null);
  10771. return samples;
  10772. };
  10773. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10774. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10775. };
  10776. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10777. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10778. };
  10779. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10780. var gl = this._gl;
  10781. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10782. var generateMipMaps = true;
  10783. var generateDepthBuffer = true;
  10784. var generateStencilBuffer = false;
  10785. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10786. if (options !== undefined) {
  10787. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10788. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10789. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10790. if (options.samplingMode !== undefined) {
  10791. samplingMode = options.samplingMode;
  10792. }
  10793. }
  10794. texture.isCube = true;
  10795. texture.generateMipMaps = generateMipMaps;
  10796. texture.samples = 1;
  10797. texture.samplingMode = samplingMode;
  10798. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10799. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10800. for (var face = 0; face < 6; face++) {
  10801. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10802. }
  10803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10804. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10806. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10807. // Create the framebuffer
  10808. var framebuffer = gl.createFramebuffer();
  10809. this.bindUnboundFramebuffer(framebuffer);
  10810. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10811. // Mipmaps
  10812. if (texture.generateMipMaps) {
  10813. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10814. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10815. }
  10816. // Unbind
  10817. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10818. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10819. this.bindUnboundFramebuffer(null);
  10820. texture._framebuffer = framebuffer;
  10821. texture.width = size;
  10822. texture.height = size;
  10823. texture.isReady = true;
  10824. this.resetTextureCache();
  10825. this._internalTexturesCache.push(texture);
  10826. return texture;
  10827. };
  10828. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10829. var _this = this;
  10830. if (onLoad === void 0) { onLoad = null; }
  10831. if (onError === void 0) { onError = null; }
  10832. if (forcedExtension === void 0) { forcedExtension = null; }
  10833. var callback = function (loadData) {
  10834. if (!loadData) {
  10835. if (onLoad) {
  10836. onLoad(null);
  10837. }
  10838. return;
  10839. }
  10840. var texture = loadData.texture;
  10841. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10842. texture._lodGenerationScale = scale;
  10843. texture._lodGenerationOffset = offset;
  10844. if (_this._caps.textureLOD) {
  10845. // Do not add extra process if texture lod is supported.
  10846. if (onLoad) {
  10847. onLoad(texture);
  10848. }
  10849. return;
  10850. }
  10851. var mipSlices = 3;
  10852. var gl = _this._gl;
  10853. var width = loadData.width;
  10854. if (!width) {
  10855. return;
  10856. }
  10857. var textures = [];
  10858. for (var i = 0; i < mipSlices; i++) {
  10859. //compute LOD from even spacing in smoothness (matching shader calculation)
  10860. var smoothness = i / (mipSlices - 1);
  10861. var roughness = 1 - smoothness;
  10862. var minLODIndex = offset; // roughness = 0
  10863. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10864. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10865. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10866. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10867. glTextureFromLod.isCube = true;
  10868. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10869. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10870. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10871. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10873. if (loadData.isDDS) {
  10874. var info = loadData.info;
  10875. var data = loadData.data;
  10876. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10877. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10878. }
  10879. else {
  10880. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10881. }
  10882. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10883. // Wrap in a base texture for easy binding.
  10884. var lodTexture = new BABYLON.BaseTexture(scene);
  10885. lodTexture.isCube = true;
  10886. lodTexture._texture = glTextureFromLod;
  10887. glTextureFromLod.isReady = true;
  10888. textures.push(lodTexture);
  10889. }
  10890. texture._lodTextureHigh = textures[2];
  10891. texture._lodTextureMid = textures[1];
  10892. texture._lodTextureLow = textures[0];
  10893. if (onLoad) {
  10894. onLoad(texture);
  10895. }
  10896. };
  10897. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10898. };
  10899. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10900. var _this = this;
  10901. if (onLoad === void 0) { onLoad = null; }
  10902. if (onError === void 0) { onError = null; }
  10903. if (forcedExtension === void 0) { forcedExtension = null; }
  10904. var gl = this._gl;
  10905. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10906. texture.isCube = true;
  10907. texture.url = rootUrl;
  10908. texture.generateMipMaps = !noMipmap;
  10909. if (!this._doNotHandleContextLost) {
  10910. texture._extension = forcedExtension;
  10911. texture._files = files;
  10912. }
  10913. var isKTX = false;
  10914. var isDDS = false;
  10915. var lastDot = rootUrl.lastIndexOf('.');
  10916. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  10917. if (this._textureFormatInUse) {
  10918. extension = this._textureFormatInUse;
  10919. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  10920. isKTX = true;
  10921. }
  10922. else {
  10923. isDDS = (extension === ".dds");
  10924. }
  10925. var onerror = function (request, exception) {
  10926. if (onError) {
  10927. onError(request.status + " " + request.statusText, exception);
  10928. }
  10929. };
  10930. if (isKTX) {
  10931. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10932. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10933. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10934. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10935. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10936. ktx.uploadLevels(_this._gl, !noMipmap);
  10937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10938. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10939. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10940. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10941. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10942. _this.resetTextureCache();
  10943. texture.width = ktx.pixelWidth;
  10944. texture.height = ktx.pixelHeight;
  10945. texture.isReady = true;
  10946. }, undefined, undefined, true, onerror);
  10947. }
  10948. else if (isDDS) {
  10949. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10950. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10951. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10952. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10953. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10954. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10955. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10956. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10957. }
  10958. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10959. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10961. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10962. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10963. _this.resetTextureCache();
  10964. texture.width = info.width;
  10965. texture.height = info.height;
  10966. texture.isReady = true;
  10967. texture.type = info.textureType;
  10968. if (onLoad) {
  10969. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10970. }
  10971. }, undefined, undefined, true, onerror);
  10972. }
  10973. else {
  10974. if (!files) {
  10975. throw new Error("Cannot load cubemap because files were not defined");
  10976. }
  10977. cascadeLoad(rootUrl, scene, function (imgs) {
  10978. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10979. var height = width;
  10980. _this._prepareWorkingCanvas();
  10981. if (!_this._workingCanvas || !_this._workingContext) {
  10982. return;
  10983. }
  10984. _this._workingCanvas.width = width;
  10985. _this._workingCanvas.height = height;
  10986. var faces = [
  10987. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10988. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10989. ];
  10990. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10991. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10992. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10993. for (var index = 0; index < faces.length; index++) {
  10994. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10995. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10996. }
  10997. if (!noMipmap) {
  10998. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10999. }
  11000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  11002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11004. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11005. _this.resetTextureCache();
  11006. texture.width = width;
  11007. texture.height = height;
  11008. texture.isReady = true;
  11009. if (format) {
  11010. texture.format = format;
  11011. }
  11012. texture.onLoadedObservable.notifyObservers(texture);
  11013. texture.onLoadedObservable.clear();
  11014. if (onLoad) {
  11015. onLoad();
  11016. }
  11017. }, files, onError);
  11018. }
  11019. this._internalTexturesCache.push(texture);
  11020. return texture;
  11021. };
  11022. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11023. if (compression === void 0) { compression = null; }
  11024. if (level === void 0) { level = 0; }
  11025. texture._bufferViewArray = data;
  11026. texture.format = format;
  11027. texture.type = type;
  11028. texture.invertY = invertY;
  11029. texture._compression = compression;
  11030. var gl = this._gl;
  11031. var textureType = this._getWebGLTextureType(type);
  11032. var internalFormat = this._getInternalFormat(format);
  11033. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11034. var needConversion = false;
  11035. if (internalFormat === gl.RGB) {
  11036. internalFormat = gl.RGBA;
  11037. needConversion = true;
  11038. }
  11039. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11040. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11041. if (texture.width % 4 !== 0) {
  11042. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11043. }
  11044. // Data are known to be in +X +Y +Z -X -Y -Z
  11045. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11046. var faceData = data[faceIndex];
  11047. if (compression) {
  11048. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11049. }
  11050. else {
  11051. if (needConversion) {
  11052. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11053. }
  11054. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11055. }
  11056. }
  11057. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11058. if (isPot && texture.generateMipMaps && level === 0) {
  11059. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11060. }
  11061. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11062. this.resetTextureCache();
  11063. texture.isReady = true;
  11064. };
  11065. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11066. if (compression === void 0) { compression = null; }
  11067. var gl = this._gl;
  11068. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11069. texture.isCube = true;
  11070. texture.generateMipMaps = generateMipMaps;
  11071. texture.format = format;
  11072. texture.type = type;
  11073. if (!this._doNotHandleContextLost) {
  11074. texture._bufferViewArray = data;
  11075. }
  11076. var textureType = this._getWebGLTextureType(type);
  11077. var internalFormat = this._getInternalFormat(format);
  11078. var needConversion = false;
  11079. if (internalFormat === gl.RGB) {
  11080. internalFormat = gl.RGBA;
  11081. needConversion = true;
  11082. }
  11083. var width = size;
  11084. var height = width;
  11085. texture.width = width;
  11086. texture.height = height;
  11087. // Double check on POT to generate Mips.
  11088. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11089. if (!isPot) {
  11090. generateMipMaps = false;
  11091. }
  11092. // Upload data if needed. The texture won't be ready until then.
  11093. if (data) {
  11094. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11095. }
  11096. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11097. // Filters
  11098. if (data && generateMipMaps) {
  11099. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11100. }
  11101. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11102. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11103. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11104. }
  11105. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11106. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11107. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11108. }
  11109. else {
  11110. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11111. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11113. }
  11114. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11115. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11116. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11117. return texture;
  11118. };
  11119. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11120. var _this = this;
  11121. if (onLoad === void 0) { onLoad = null; }
  11122. if (onError === void 0) { onError = null; }
  11123. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11124. if (invertY === void 0) { invertY = false; }
  11125. var gl = this._gl;
  11126. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11127. scene._addPendingData(texture);
  11128. texture.url = url;
  11129. this._internalTexturesCache.push(texture);
  11130. var onerror = function (request, exception) {
  11131. scene._removePendingData(texture);
  11132. if (onError) {
  11133. onError(request.status + " " + request.statusText, exception);
  11134. }
  11135. };
  11136. var internalCallback = function (data) {
  11137. var width = texture.width;
  11138. var faceDataArrays = callback(data);
  11139. if (!faceDataArrays) {
  11140. return;
  11141. }
  11142. if (mipmmapGenerator) {
  11143. var textureType = _this._getWebGLTextureType(type);
  11144. var internalFormat = _this._getInternalFormat(format);
  11145. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11146. var needConversion = false;
  11147. if (internalFormat === gl.RGB) {
  11148. internalFormat = gl.RGBA;
  11149. needConversion = true;
  11150. }
  11151. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11152. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11153. var mipData = mipmmapGenerator(faceDataArrays);
  11154. for (var level = 0; level < mipData.length; level++) {
  11155. var mipSize = width >> level;
  11156. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11157. var mipFaceData = mipData[level][faceIndex];
  11158. if (needConversion) {
  11159. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11160. }
  11161. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11162. }
  11163. }
  11164. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11165. }
  11166. else {
  11167. texture.generateMipMaps = !noMipmap;
  11168. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11169. }
  11170. texture.isReady = true;
  11171. _this.resetTextureCache();
  11172. scene._removePendingData(texture);
  11173. if (onLoad) {
  11174. onLoad();
  11175. }
  11176. };
  11177. BABYLON.Tools.LoadFile(url, function (data) {
  11178. internalCallback(data);
  11179. }, undefined, scene.database, true, onerror);
  11180. return texture;
  11181. };
  11182. ;
  11183. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11184. if (compression === void 0) { compression = null; }
  11185. var internalFormat = this._getInternalFormat(format);
  11186. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11187. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11188. if (!this._doNotHandleContextLost) {
  11189. texture._bufferView = data;
  11190. texture.format = format;
  11191. texture.invertY = invertY;
  11192. texture._compression = compression;
  11193. }
  11194. if (texture.width % 4 !== 0) {
  11195. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11196. }
  11197. if (compression && data) {
  11198. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11199. }
  11200. else {
  11201. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11202. }
  11203. if (texture.generateMipMaps) {
  11204. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11205. }
  11206. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11207. this.resetTextureCache();
  11208. texture.isReady = true;
  11209. };
  11210. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11211. if (compression === void 0) { compression = null; }
  11212. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11213. texture.baseWidth = width;
  11214. texture.baseHeight = height;
  11215. texture.baseDepth = depth;
  11216. texture.width = width;
  11217. texture.height = height;
  11218. texture.depth = depth;
  11219. texture.format = format;
  11220. texture.generateMipMaps = generateMipMaps;
  11221. texture.samplingMode = samplingMode;
  11222. texture.is3D = true;
  11223. if (!this._doNotHandleContextLost) {
  11224. texture._bufferView = data;
  11225. }
  11226. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11227. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11228. // Filters
  11229. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11230. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11231. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11232. if (generateMipMaps) {
  11233. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11234. }
  11235. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11236. this._internalTexturesCache.push(texture);
  11237. return texture;
  11238. };
  11239. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11240. var gl = this._gl;
  11241. if (!gl) {
  11242. return;
  11243. }
  11244. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11245. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11246. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11247. if (!noMipmap && !isCompressed) {
  11248. gl.generateMipmap(gl.TEXTURE_2D);
  11249. }
  11250. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11251. this.resetTextureCache();
  11252. if (scene) {
  11253. scene._removePendingData(texture);
  11254. }
  11255. texture.onLoadedObservable.notifyObservers(texture);
  11256. texture.onLoadedObservable.clear();
  11257. };
  11258. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11259. var _this = this;
  11260. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11261. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11262. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11263. var gl = this._gl;
  11264. if (!gl) {
  11265. return;
  11266. }
  11267. if (!texture._webGLTexture) {
  11268. this.resetTextureCache();
  11269. if (scene) {
  11270. scene._removePendingData(texture);
  11271. }
  11272. return;
  11273. }
  11274. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11275. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11276. texture.baseWidth = width;
  11277. texture.baseHeight = height;
  11278. texture.width = potWidth;
  11279. texture.height = potHeight;
  11280. texture.isReady = true;
  11281. if (processFunction(potWidth, potHeight, function () {
  11282. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11283. })) {
  11284. // Returning as texture needs extra async steps
  11285. return;
  11286. }
  11287. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11288. };
  11289. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11290. // Create new RGBA data container.
  11291. var rgbaData;
  11292. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11293. rgbaData = new Float32Array(width * height * 4);
  11294. }
  11295. else {
  11296. rgbaData = new Uint32Array(width * height * 4);
  11297. }
  11298. // Convert each pixel.
  11299. for (var x = 0; x < width; x++) {
  11300. for (var y = 0; y < height; y++) {
  11301. var index = (y * width + x) * 3;
  11302. var newIndex = (y * width + x) * 4;
  11303. // Map Old Value to new value.
  11304. rgbaData[newIndex + 0] = rgbData[index + 0];
  11305. rgbaData[newIndex + 1] = rgbData[index + 1];
  11306. rgbaData[newIndex + 2] = rgbData[index + 2];
  11307. // Add fully opaque alpha channel.
  11308. rgbaData[newIndex + 3] = 1;
  11309. }
  11310. }
  11311. return rgbaData;
  11312. };
  11313. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11314. var gl = this._gl;
  11315. if (texture._framebuffer) {
  11316. gl.deleteFramebuffer(texture._framebuffer);
  11317. texture._framebuffer = null;
  11318. }
  11319. if (texture._depthStencilBuffer) {
  11320. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11321. texture._depthStencilBuffer = null;
  11322. }
  11323. if (texture._MSAAFramebuffer) {
  11324. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11325. texture._MSAAFramebuffer = null;
  11326. }
  11327. if (texture._MSAARenderBuffer) {
  11328. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11329. texture._MSAARenderBuffer = null;
  11330. }
  11331. };
  11332. Engine.prototype._releaseTexture = function (texture) {
  11333. var gl = this._gl;
  11334. this._releaseFramebufferObjects(texture);
  11335. gl.deleteTexture(texture._webGLTexture);
  11336. // Unbind channels
  11337. this.unbindAllTextures();
  11338. var index = this._internalTexturesCache.indexOf(texture);
  11339. if (index !== -1) {
  11340. this._internalTexturesCache.splice(index, 1);
  11341. }
  11342. // Integrated fixed lod samplers.
  11343. if (texture._lodTextureHigh) {
  11344. texture._lodTextureHigh.dispose();
  11345. }
  11346. if (texture._lodTextureMid) {
  11347. texture._lodTextureMid.dispose();
  11348. }
  11349. if (texture._lodTextureLow) {
  11350. texture._lodTextureLow.dispose();
  11351. }
  11352. };
  11353. Engine.prototype.setProgram = function (program) {
  11354. if (this._currentProgram !== program) {
  11355. this._gl.useProgram(program);
  11356. this._currentProgram = program;
  11357. }
  11358. };
  11359. Engine.prototype.bindSamplers = function (effect) {
  11360. this.setProgram(effect.getProgram());
  11361. var samplers = effect.getSamplers();
  11362. for (var index = 0; index < samplers.length; index++) {
  11363. var uniform = effect.getUniform(samplers[index]);
  11364. this._gl.uniform1i(uniform, index);
  11365. }
  11366. this._currentEffect = null;
  11367. };
  11368. Engine.prototype.activateTexture = function (texture) {
  11369. if (this._activeTexture !== texture) {
  11370. this._gl.activeTexture(texture);
  11371. this._activeTexture = texture;
  11372. }
  11373. };
  11374. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11375. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  11376. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11377. this._activeTexturesCache[this._activeTexture] = texture;
  11378. }
  11379. };
  11380. Engine.prototype._bindTexture = function (channel, texture) {
  11381. if (channel < 0) {
  11382. return;
  11383. }
  11384. this.activateTexture(this._gl.TEXTURE0 + channel);
  11385. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11386. };
  11387. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11388. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11389. };
  11390. Engine.prototype.unbindAllTextures = function () {
  11391. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11392. this.activateTexture(this._gl["TEXTURE" + channel]);
  11393. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11394. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11395. if (this.webGLVersion > 1) {
  11396. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11397. }
  11398. }
  11399. };
  11400. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11401. if (channel < 0) {
  11402. return;
  11403. }
  11404. this._gl.uniform1i(uniform, channel);
  11405. this._setTexture(channel, texture);
  11406. };
  11407. Engine.prototype._setTexture = function (channel, texture) {
  11408. // Not ready?
  11409. if (!texture) {
  11410. if (this._activeTexturesCache[channel] != null) {
  11411. this.activateTexture(this._gl["TEXTURE" + channel]);
  11412. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11413. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11414. if (this.webGLVersion > 1) {
  11415. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11416. }
  11417. }
  11418. return;
  11419. }
  11420. // Video
  11421. var alreadyActivated = false;
  11422. if (texture.video) {
  11423. this.activateTexture(this._gl["TEXTURE" + channel]);
  11424. alreadyActivated = true;
  11425. texture.update();
  11426. }
  11427. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11428. texture.delayLoad();
  11429. return;
  11430. }
  11431. var internalTexture;
  11432. if (texture.isReady()) {
  11433. internalTexture = texture.getInternalTexture();
  11434. }
  11435. else if (texture.isCube) {
  11436. internalTexture = this.emptyCubeTexture;
  11437. }
  11438. else if (texture.is3D) {
  11439. internalTexture = this.emptyTexture3D;
  11440. }
  11441. else {
  11442. internalTexture = this.emptyTexture;
  11443. }
  11444. if (this._activeTexturesCache[channel] === internalTexture) {
  11445. return;
  11446. }
  11447. if (!alreadyActivated) {
  11448. this.activateTexture(this._gl["TEXTURE" + channel]);
  11449. }
  11450. if (internalTexture && internalTexture.is3D) {
  11451. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11452. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11453. internalTexture._cachedWrapU = texture.wrapU;
  11454. switch (texture.wrapU) {
  11455. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11456. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11457. break;
  11458. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11459. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11460. break;
  11461. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11462. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11463. break;
  11464. }
  11465. }
  11466. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11467. internalTexture._cachedWrapV = texture.wrapV;
  11468. switch (texture.wrapV) {
  11469. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11470. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11471. break;
  11472. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11473. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11474. break;
  11475. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11476. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11477. break;
  11478. }
  11479. }
  11480. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11481. internalTexture._cachedWrapR = texture.wrapR;
  11482. switch (texture.wrapV) {
  11483. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11484. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11485. break;
  11486. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11487. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11488. break;
  11489. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11490. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11491. break;
  11492. }
  11493. }
  11494. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11495. }
  11496. else if (internalTexture && internalTexture.isCube) {
  11497. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11498. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11499. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11500. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11501. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11502. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11503. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11504. }
  11505. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11506. }
  11507. else {
  11508. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11509. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11510. internalTexture._cachedWrapU = texture.wrapU;
  11511. switch (texture.wrapU) {
  11512. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11513. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11514. break;
  11515. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11516. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11517. break;
  11518. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11519. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11520. break;
  11521. }
  11522. }
  11523. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11524. internalTexture._cachedWrapV = texture.wrapV;
  11525. switch (texture.wrapV) {
  11526. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11527. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11528. break;
  11529. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11530. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11531. break;
  11532. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11533. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11534. break;
  11535. }
  11536. }
  11537. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11538. }
  11539. };
  11540. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11541. if (channel < 0 || !uniform) {
  11542. return;
  11543. }
  11544. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11545. this._textureUnits = new Int32Array(textures.length);
  11546. }
  11547. for (var i = 0; i < textures.length; i++) {
  11548. this._textureUnits[i] = channel + i;
  11549. }
  11550. this._gl.uniform1iv(uniform, this._textureUnits);
  11551. for (var index = 0; index < textures.length; index++) {
  11552. this._setTexture(channel + index, textures[index]);
  11553. }
  11554. };
  11555. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11556. var internalTexture = texture.getInternalTexture();
  11557. if (!internalTexture) {
  11558. return;
  11559. }
  11560. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11561. var value = texture.anisotropicFilteringLevel;
  11562. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11563. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11564. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11565. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11566. }
  11567. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11568. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11569. internalTexture._cachedAnisotropicFilteringLevel = value;
  11570. }
  11571. };
  11572. Engine.prototype.readPixels = function (x, y, width, height) {
  11573. var data = new Uint8Array(height * width * 4);
  11574. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11575. return data;
  11576. };
  11577. /**
  11578. * Add an externaly attached data from its key.
  11579. * This method call will fail and return false, if such key already exists.
  11580. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11581. * @param key the unique key that identifies the data
  11582. * @param data the data object to associate to the key for this Engine instance
  11583. * @return true if no such key were already present and the data was added successfully, false otherwise
  11584. */
  11585. Engine.prototype.addExternalData = function (key, data) {
  11586. if (!this._externalData) {
  11587. this._externalData = new BABYLON.StringDictionary();
  11588. }
  11589. return this._externalData.add(key, data);
  11590. };
  11591. /**
  11592. * Get an externaly attached data from its key
  11593. * @param key the unique key that identifies the data
  11594. * @return the associated data, if present (can be null), or undefined if not present
  11595. */
  11596. Engine.prototype.getExternalData = function (key) {
  11597. if (!this._externalData) {
  11598. this._externalData = new BABYLON.StringDictionary();
  11599. }
  11600. return this._externalData.get(key);
  11601. };
  11602. /**
  11603. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11604. * @param key the unique key that identifies the data
  11605. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11606. * @return the associated data, can be null if the factory returned null.
  11607. */
  11608. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11609. if (!this._externalData) {
  11610. this._externalData = new BABYLON.StringDictionary();
  11611. }
  11612. return this._externalData.getOrAddWithFactory(key, factory);
  11613. };
  11614. /**
  11615. * Remove an externaly attached data from the Engine instance
  11616. * @param key the unique key that identifies the data
  11617. * @return true if the data was successfully removed, false if it doesn't exist
  11618. */
  11619. Engine.prototype.removeExternalData = function (key) {
  11620. if (!this._externalData) {
  11621. this._externalData = new BABYLON.StringDictionary();
  11622. }
  11623. return this._externalData.remove(key);
  11624. };
  11625. Engine.prototype.unbindAllAttributes = function () {
  11626. if (this._mustWipeVertexAttributes) {
  11627. this._mustWipeVertexAttributes = false;
  11628. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11629. this._gl.disableVertexAttribArray(i);
  11630. this._vertexAttribArraysEnabled[i] = false;
  11631. this._currentBufferPointers[i].active = false;
  11632. }
  11633. return;
  11634. }
  11635. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11636. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11637. continue;
  11638. }
  11639. this._gl.disableVertexAttribArray(i);
  11640. this._vertexAttribArraysEnabled[i] = false;
  11641. this._currentBufferPointers[i].active = false;
  11642. }
  11643. };
  11644. Engine.prototype.releaseEffects = function () {
  11645. for (var name in this._compiledEffects) {
  11646. this._deleteProgram(this._compiledEffects[name]._program);
  11647. }
  11648. this._compiledEffects = {};
  11649. };
  11650. // Dispose
  11651. Engine.prototype.dispose = function () {
  11652. this.hideLoadingUI();
  11653. this.stopRenderLoop();
  11654. // Release postProcesses
  11655. while (this.postProcesses.length) {
  11656. this.postProcesses[0].dispose();
  11657. }
  11658. // Empty texture
  11659. if (this._emptyTexture) {
  11660. this._releaseTexture(this._emptyTexture);
  11661. this._emptyTexture = null;
  11662. }
  11663. if (this._emptyCubeTexture) {
  11664. this._releaseTexture(this._emptyCubeTexture);
  11665. this._emptyCubeTexture = null;
  11666. }
  11667. // Rescale PP
  11668. if (this._rescalePostProcess) {
  11669. this._rescalePostProcess.dispose();
  11670. }
  11671. // Release scenes
  11672. while (this.scenes.length) {
  11673. this.scenes[0].dispose();
  11674. }
  11675. // Release audio engine
  11676. if (Engine.audioEngine) {
  11677. Engine.audioEngine.dispose();
  11678. }
  11679. // Release effects
  11680. this.releaseEffects();
  11681. // Unbind
  11682. this.unbindAllAttributes();
  11683. if (this._dummyFramebuffer) {
  11684. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11685. }
  11686. //WebVR
  11687. this.disableVR();
  11688. // Events
  11689. window.removeEventListener("blur", this._onBlur);
  11690. window.removeEventListener("focus", this._onFocus);
  11691. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11692. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11693. if (this._renderingCanvas) {
  11694. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11695. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11696. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11697. if (!this._doNotHandleContextLost) {
  11698. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11699. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11700. }
  11701. }
  11702. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11703. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11704. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11705. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11706. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11707. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11708. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11709. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11710. if (this._onVrDisplayConnect) {
  11711. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11712. if (this._onVrDisplayDisconnect) {
  11713. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11714. }
  11715. if (this._onVrDisplayPresentChange) {
  11716. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11717. }
  11718. this._onVrDisplayConnect = null;
  11719. this._onVrDisplayDisconnect = null;
  11720. }
  11721. // Remove from Instances
  11722. var index = Engine.Instances.indexOf(this);
  11723. if (index >= 0) {
  11724. Engine.Instances.splice(index, 1);
  11725. }
  11726. this._workingCanvas = null;
  11727. this._workingContext = null;
  11728. this._currentBufferPointers = [];
  11729. this._renderingCanvas = null;
  11730. this._currentProgram = null;
  11731. this.onResizeObservable.clear();
  11732. this.onCanvasBlurObservable.clear();
  11733. this.onCanvasFocusObservable.clear();
  11734. this.onCanvasPointerOutObservable.clear();
  11735. this.onBeginFrameObservable.clear();
  11736. this.onEndFrameObservable.clear();
  11737. BABYLON.Effect.ResetCache();
  11738. };
  11739. // Loading screen
  11740. Engine.prototype.displayLoadingUI = function () {
  11741. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11742. return;
  11743. }
  11744. var loadingScreen = this.loadingScreen;
  11745. if (loadingScreen) {
  11746. loadingScreen.displayLoadingUI();
  11747. }
  11748. };
  11749. Engine.prototype.hideLoadingUI = function () {
  11750. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11751. return;
  11752. }
  11753. var loadingScreen = this.loadingScreen;
  11754. if (loadingScreen) {
  11755. loadingScreen.hideLoadingUI();
  11756. }
  11757. };
  11758. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11759. get: function () {
  11760. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11761. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11762. return this._loadingScreen;
  11763. },
  11764. set: function (loadingScreen) {
  11765. this._loadingScreen = loadingScreen;
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11771. set: function (text) {
  11772. this.loadingScreen.loadingUIText = text;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11778. set: function (color) {
  11779. this.loadingScreen.loadingUIBackgroundColor = color;
  11780. },
  11781. enumerable: true,
  11782. configurable: true
  11783. });
  11784. Engine.prototype.attachContextLostEvent = function (callback) {
  11785. if (this._renderingCanvas) {
  11786. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11787. }
  11788. };
  11789. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11790. if (this._renderingCanvas) {
  11791. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11792. }
  11793. };
  11794. Engine.prototype.getVertexShaderSource = function (program) {
  11795. var shaders = this._gl.getAttachedShaders(program);
  11796. if (!shaders) {
  11797. return null;
  11798. }
  11799. return this._gl.getShaderSource(shaders[0]);
  11800. };
  11801. Engine.prototype.getFragmentShaderSource = function (program) {
  11802. var shaders = this._gl.getAttachedShaders(program);
  11803. if (!shaders) {
  11804. return null;
  11805. }
  11806. return this._gl.getShaderSource(shaders[1]);
  11807. };
  11808. Engine.prototype.getError = function () {
  11809. return this._gl.getError();
  11810. };
  11811. // FPS
  11812. Engine.prototype.getFps = function () {
  11813. return this._fps;
  11814. };
  11815. Engine.prototype.getDeltaTime = function () {
  11816. return this._deltaTime;
  11817. };
  11818. Engine.prototype._measureFps = function () {
  11819. this._performanceMonitor.sampleFrame();
  11820. this._fps = this._performanceMonitor.averageFPS;
  11821. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11822. };
  11823. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11824. if (faceIndex === void 0) { faceIndex = -1; }
  11825. var gl = this._gl;
  11826. if (!this._dummyFramebuffer) {
  11827. var dummy = gl.createFramebuffer();
  11828. if (!dummy) {
  11829. throw new Error("Unable to create dummy framebuffer");
  11830. }
  11831. this._dummyFramebuffer = dummy;
  11832. }
  11833. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11834. if (faceIndex > -1) {
  11835. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11836. }
  11837. else {
  11838. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11839. }
  11840. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11841. var buffer;
  11842. switch (readType) {
  11843. case gl.UNSIGNED_BYTE:
  11844. buffer = new Uint8Array(4 * width * height);
  11845. readType = gl.UNSIGNED_BYTE;
  11846. break;
  11847. default:
  11848. buffer = new Float32Array(4 * width * height);
  11849. readType = gl.FLOAT;
  11850. break;
  11851. }
  11852. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11853. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11854. return buffer;
  11855. };
  11856. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11857. if (this._webGLVersion > 1) {
  11858. return this._caps.colorBufferFloat;
  11859. }
  11860. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11861. };
  11862. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11863. if (this._webGLVersion > 1) {
  11864. return this._caps.colorBufferFloat;
  11865. }
  11866. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11867. };
  11868. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11869. Engine.prototype._canRenderToFramebuffer = function (type) {
  11870. var gl = this._gl;
  11871. //clear existing errors
  11872. while (gl.getError() !== gl.NO_ERROR) { }
  11873. var successful = true;
  11874. var texture = gl.createTexture();
  11875. gl.bindTexture(gl.TEXTURE_2D, texture);
  11876. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11877. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11878. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11879. var fb = gl.createFramebuffer();
  11880. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11881. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11882. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11883. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11884. successful = successful && (gl.getError() === gl.NO_ERROR);
  11885. //try render by clearing frame buffer's color buffer
  11886. if (successful) {
  11887. gl.clear(gl.COLOR_BUFFER_BIT);
  11888. successful = successful && (gl.getError() === gl.NO_ERROR);
  11889. }
  11890. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11891. if (successful) {
  11892. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11893. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11894. var readFormat = gl.RGBA;
  11895. var readType = gl.UNSIGNED_BYTE;
  11896. var buffer = new Uint8Array(4);
  11897. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11898. successful = successful && (gl.getError() === gl.NO_ERROR);
  11899. }
  11900. //clean up
  11901. gl.deleteTexture(texture);
  11902. gl.deleteFramebuffer(fb);
  11903. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11904. //clear accumulated errors
  11905. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11906. return successful;
  11907. };
  11908. Engine.prototype._getWebGLTextureType = function (type) {
  11909. if (type === Engine.TEXTURETYPE_FLOAT) {
  11910. return this._gl.FLOAT;
  11911. }
  11912. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11913. // Add Half Float Constant.
  11914. return this._gl.HALF_FLOAT_OES;
  11915. }
  11916. return this._gl.UNSIGNED_BYTE;
  11917. };
  11918. ;
  11919. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11920. if (this._webGLVersion === 1) {
  11921. return this._gl.RGBA;
  11922. }
  11923. if (type === Engine.TEXTURETYPE_FLOAT) {
  11924. return this._gl.RGBA32F;
  11925. }
  11926. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11927. return this._gl.RGBA16F;
  11928. }
  11929. return this._gl.RGBA;
  11930. };
  11931. ;
  11932. Engine.prototype.createQuery = function () {
  11933. return this._gl.createQuery();
  11934. };
  11935. Engine.prototype.deleteQuery = function (query) {
  11936. this._gl.deleteQuery(query);
  11937. return this;
  11938. };
  11939. Engine.prototype.isQueryResultAvailable = function (query) {
  11940. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11941. };
  11942. Engine.prototype.getQueryResult = function (query) {
  11943. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11944. };
  11945. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  11946. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11947. this._gl.beginQuery(glAlgorithm, query);
  11948. return this;
  11949. };
  11950. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  11951. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11952. this._gl.endQuery(glAlgorithm);
  11953. return this;
  11954. };
  11955. /* Time queries */
  11956. Engine.prototype._createTimeQuery = function () {
  11957. var timerQuery = this._caps.timerQuery;
  11958. if (timerQuery.createQueryEXT) {
  11959. return timerQuery.createQueryEXT();
  11960. }
  11961. return this.createQuery();
  11962. };
  11963. Engine.prototype._deleteTimeQuery = function (query) {
  11964. var timerQuery = this._caps.timerQuery;
  11965. if (timerQuery.deleteQueryEXT) {
  11966. timerQuery.deleteQueryEXT(query);
  11967. return;
  11968. }
  11969. this.deleteQuery(query);
  11970. };
  11971. Engine.prototype._getTimeQueryResult = function (query) {
  11972. var timerQuery = this._caps.timerQuery;
  11973. if (timerQuery.getQueryObjectEXT) {
  11974. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  11975. }
  11976. return this.getQueryResult(query);
  11977. };
  11978. Engine.prototype._getTimeQueryAvailability = function (query) {
  11979. var timerQuery = this._caps.timerQuery;
  11980. if (timerQuery.getQueryObjectEXT) {
  11981. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  11982. }
  11983. return this.isQueryResultAvailable(query);
  11984. };
  11985. Engine.prototype.startTimeQuery = function () {
  11986. var timerQuery = this._caps.timerQuery;
  11987. if (!timerQuery) {
  11988. return null;
  11989. }
  11990. var token = new BABYLON._TimeToken();
  11991. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  11992. if (this._caps.canUseTimestampForTimerQuery) {
  11993. token._startTimeQuery = this._createTimeQuery();
  11994. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  11995. }
  11996. else {
  11997. if (this._currentNonTimestampToken) {
  11998. return this._currentNonTimestampToken;
  11999. }
  12000. token._timeElapsedQuery = this._createTimeQuery();
  12001. if (timerQuery.beginQueryEXT) {
  12002. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12003. }
  12004. else {
  12005. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12006. }
  12007. this._currentNonTimestampToken = token;
  12008. }
  12009. return token;
  12010. };
  12011. Engine.prototype.endTimeQuery = function (token) {
  12012. var timerQuery = this._caps.timerQuery;
  12013. if (!timerQuery || !token) {
  12014. return -1;
  12015. }
  12016. if (this._caps.canUseTimestampForTimerQuery) {
  12017. if (!token._startTimeQuery) {
  12018. return -1;
  12019. }
  12020. if (!token._endTimeQuery) {
  12021. token._endTimeQuery = this._createTimeQuery();
  12022. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12023. }
  12024. }
  12025. else if (!token._timeElapsedQueryEnded) {
  12026. if (!token._timeElapsedQuery) {
  12027. return -1;
  12028. }
  12029. if (timerQuery.endQueryEXT) {
  12030. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12031. }
  12032. else {
  12033. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12034. }
  12035. token._timeElapsedQueryEnded = true;
  12036. }
  12037. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12038. var available = false;
  12039. if (token._endTimeQuery) {
  12040. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12041. }
  12042. else if (token._timeElapsedQuery) {
  12043. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12044. }
  12045. if (available && !disjoint) {
  12046. var result = 0;
  12047. if (this._caps.canUseTimestampForTimerQuery) {
  12048. if (!token._startTimeQuery || !token._endTimeQuery) {
  12049. return -1;
  12050. }
  12051. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12052. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12053. result = timeEnd - timeStart;
  12054. this._deleteTimeQuery(token._startTimeQuery);
  12055. this._deleteTimeQuery(token._endTimeQuery);
  12056. token._startTimeQuery = null;
  12057. token._endTimeQuery = null;
  12058. }
  12059. else {
  12060. if (!token._timeElapsedQuery) {
  12061. return -1;
  12062. }
  12063. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12064. this._deleteTimeQuery(token._timeElapsedQuery);
  12065. token._timeElapsedQuery = null;
  12066. token._timeElapsedQueryEnded = false;
  12067. this._currentNonTimestampToken = null;
  12068. }
  12069. return result;
  12070. }
  12071. return -1;
  12072. };
  12073. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12074. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12075. };
  12076. // Transform feedback
  12077. Engine.prototype.createTransformFeedback = function () {
  12078. return this._gl.createTransformFeedback();
  12079. };
  12080. Engine.prototype.deleteTransformFeedback = function (value) {
  12081. this._gl.deleteTransformFeedback(value);
  12082. };
  12083. Engine.prototype.bindTransformFeedback = function (value) {
  12084. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12085. };
  12086. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12087. if (usePoints === void 0) { usePoints = true; }
  12088. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12089. };
  12090. Engine.prototype.endTransformFeedback = function () {
  12091. this._gl.endTransformFeedback();
  12092. };
  12093. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12094. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12095. };
  12096. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12097. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12098. };
  12099. // Statics
  12100. Engine.isSupported = function () {
  12101. try {
  12102. var tempcanvas = document.createElement("canvas");
  12103. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12104. return gl != null && !!window.WebGLRenderingContext;
  12105. }
  12106. catch (e) {
  12107. return false;
  12108. }
  12109. };
  12110. Engine.Instances = new Array();
  12111. // Const statics
  12112. Engine._ALPHA_DISABLE = 0;
  12113. Engine._ALPHA_ADD = 1;
  12114. Engine._ALPHA_COMBINE = 2;
  12115. Engine._ALPHA_SUBTRACT = 3;
  12116. Engine._ALPHA_MULTIPLY = 4;
  12117. Engine._ALPHA_MAXIMIZED = 5;
  12118. Engine._ALPHA_ONEONE = 6;
  12119. Engine._ALPHA_PREMULTIPLIED = 7;
  12120. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12121. Engine._ALPHA_INTERPOLATE = 9;
  12122. Engine._ALPHA_SCREENMODE = 10;
  12123. Engine._DELAYLOADSTATE_NONE = 0;
  12124. Engine._DELAYLOADSTATE_LOADED = 1;
  12125. Engine._DELAYLOADSTATE_LOADING = 2;
  12126. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12127. Engine._TEXTUREFORMAT_ALPHA = 0;
  12128. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12129. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12130. Engine._TEXTUREFORMAT_RGB = 4;
  12131. Engine._TEXTUREFORMAT_RGBA = 5;
  12132. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12133. Engine._TEXTURETYPE_FLOAT = 1;
  12134. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12135. // Depht or Stencil test Constants.
  12136. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12137. 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.
  12138. 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.
  12139. 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.
  12140. 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.
  12141. 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.
  12142. 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.
  12143. 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.
  12144. // Stencil Actions Constants.
  12145. Engine._KEEP = 0x1E00;
  12146. Engine._REPLACE = 0x1E01;
  12147. Engine._INCR = 0x1E02;
  12148. Engine._DECR = 0x1E03;
  12149. Engine._INVERT = 0x150A;
  12150. Engine._INCR_WRAP = 0x8507;
  12151. Engine._DECR_WRAP = 0x8508;
  12152. // Texture rescaling mode
  12153. Engine._SCALEMODE_FLOOR = 1;
  12154. Engine._SCALEMODE_NEAREST = 2;
  12155. Engine._SCALEMODE_CEILING = 3;
  12156. // Updatable statics so stick with vars here
  12157. Engine.CollisionsEpsilon = 0.001;
  12158. Engine.CodeRepository = "src/";
  12159. Engine.ShadersRepository = "src/Shaders/";
  12160. return Engine;
  12161. }());
  12162. BABYLON.Engine = Engine;
  12163. })(BABYLON || (BABYLON = {}));
  12164. //# sourceMappingURL=babylon.engine.js.map
  12165. var BABYLON;
  12166. (function (BABYLON) {
  12167. /**
  12168. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12169. */
  12170. var Node = /** @class */ (function () {
  12171. /**
  12172. * @constructor
  12173. * @param {string} name - the name and id to be given to this node
  12174. * @param {BABYLON.Scene} the scene this node will be added to
  12175. */
  12176. function Node(name, scene) {
  12177. if (scene === void 0) { scene = null; }
  12178. this.state = "";
  12179. this.metadata = null;
  12180. this.doNotSerialize = false;
  12181. this.animations = new Array();
  12182. this._ranges = {};
  12183. this._isEnabled = true;
  12184. this._isReady = true;
  12185. this._currentRenderId = -1;
  12186. this._parentRenderId = -1;
  12187. /**
  12188. * An event triggered when the mesh is disposed.
  12189. * @type {BABYLON.Observable}
  12190. */
  12191. this.onDisposeObservable = new BABYLON.Observable();
  12192. // Behaviors
  12193. this._behaviors = new Array();
  12194. this.name = name;
  12195. this.id = name;
  12196. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12197. this.uniqueId = this._scene.getUniqueId();
  12198. this._initCache();
  12199. }
  12200. Object.defineProperty(Node.prototype, "parent", {
  12201. get: function () {
  12202. return this._parentNode;
  12203. },
  12204. set: function (parent) {
  12205. if (this._parentNode === parent) {
  12206. return;
  12207. }
  12208. if (this._parentNode) {
  12209. var index = this._parentNode._children.indexOf(this);
  12210. if (index !== -1) {
  12211. this._parentNode._children.splice(index, 1);
  12212. }
  12213. }
  12214. this._parentNode = parent;
  12215. if (this._parentNode) {
  12216. if (!this._parentNode._children) {
  12217. this._parentNode._children = new Array();
  12218. }
  12219. this._parentNode._children.push(this);
  12220. }
  12221. },
  12222. enumerable: true,
  12223. configurable: true
  12224. });
  12225. Node.prototype.getClassName = function () {
  12226. return "Node";
  12227. };
  12228. Object.defineProperty(Node.prototype, "onDispose", {
  12229. set: function (callback) {
  12230. if (this._onDisposeObserver) {
  12231. this.onDisposeObservable.remove(this._onDisposeObserver);
  12232. }
  12233. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12234. },
  12235. enumerable: true,
  12236. configurable: true
  12237. });
  12238. Node.prototype.getScene = function () {
  12239. return this._scene;
  12240. };
  12241. Node.prototype.getEngine = function () {
  12242. return this._scene.getEngine();
  12243. };
  12244. Node.prototype.addBehavior = function (behavior) {
  12245. var index = this._behaviors.indexOf(behavior);
  12246. if (index !== -1) {
  12247. return this;
  12248. }
  12249. behavior.attach(this);
  12250. this._behaviors.push(behavior);
  12251. return this;
  12252. };
  12253. Node.prototype.removeBehavior = function (behavior) {
  12254. var index = this._behaviors.indexOf(behavior);
  12255. if (index === -1) {
  12256. return this;
  12257. }
  12258. this._behaviors[index].detach();
  12259. this._behaviors.splice(index, 1);
  12260. return this;
  12261. };
  12262. Object.defineProperty(Node.prototype, "behaviors", {
  12263. get: function () {
  12264. return this._behaviors;
  12265. },
  12266. enumerable: true,
  12267. configurable: true
  12268. });
  12269. Node.prototype.getBehaviorByName = function (name) {
  12270. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12271. var behavior = _a[_i];
  12272. if (behavior.name === name) {
  12273. return behavior;
  12274. }
  12275. }
  12276. return null;
  12277. };
  12278. // override it in derived class
  12279. Node.prototype.getWorldMatrix = function () {
  12280. return BABYLON.Matrix.Identity();
  12281. };
  12282. // override it in derived class if you add new variables to the cache
  12283. // and call the parent class method
  12284. Node.prototype._initCache = function () {
  12285. this._cache = {};
  12286. this._cache.parent = undefined;
  12287. };
  12288. Node.prototype.updateCache = function (force) {
  12289. if (!force && this.isSynchronized())
  12290. return;
  12291. this._cache.parent = this.parent;
  12292. this._updateCache();
  12293. };
  12294. // override it in derived class if you add new variables to the cache
  12295. // and call the parent class method if !ignoreParentClass
  12296. Node.prototype._updateCache = function (ignoreParentClass) {
  12297. };
  12298. // override it in derived class if you add new variables to the cache
  12299. Node.prototype._isSynchronized = function () {
  12300. return true;
  12301. };
  12302. Node.prototype._markSyncedWithParent = function () {
  12303. if (this.parent) {
  12304. this._parentRenderId = this.parent._currentRenderId;
  12305. }
  12306. };
  12307. Node.prototype.isSynchronizedWithParent = function () {
  12308. if (!this.parent) {
  12309. return true;
  12310. }
  12311. if (this._parentRenderId !== this.parent._currentRenderId) {
  12312. return false;
  12313. }
  12314. return this.parent.isSynchronized();
  12315. };
  12316. Node.prototype.isSynchronized = function (updateCache) {
  12317. var check = this.hasNewParent();
  12318. check = check || !this.isSynchronizedWithParent();
  12319. check = check || !this._isSynchronized();
  12320. if (updateCache)
  12321. this.updateCache(true);
  12322. return !check;
  12323. };
  12324. Node.prototype.hasNewParent = function (update) {
  12325. if (this._cache.parent === this.parent)
  12326. return false;
  12327. if (update)
  12328. this._cache.parent = this.parent;
  12329. return true;
  12330. };
  12331. /**
  12332. * Is this node ready to be used/rendered
  12333. * @return {boolean} is it ready
  12334. */
  12335. Node.prototype.isReady = function () {
  12336. return this._isReady;
  12337. };
  12338. /**
  12339. * Is this node enabled.
  12340. * If the node has a parent and is enabled, the parent will be inspected as well.
  12341. * @return {boolean} whether this node (and its parent) is enabled.
  12342. * @see setEnabled
  12343. */
  12344. Node.prototype.isEnabled = function () {
  12345. if (!this._isEnabled) {
  12346. return false;
  12347. }
  12348. if (this.parent) {
  12349. return this.parent.isEnabled();
  12350. }
  12351. return true;
  12352. };
  12353. /**
  12354. * Set the enabled state of this node.
  12355. * @param {boolean} value - the new enabled state
  12356. * @see isEnabled
  12357. */
  12358. Node.prototype.setEnabled = function (value) {
  12359. this._isEnabled = value;
  12360. };
  12361. /**
  12362. * Is this node a descendant of the given node.
  12363. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12364. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12365. * @see parent
  12366. */
  12367. Node.prototype.isDescendantOf = function (ancestor) {
  12368. if (this.parent) {
  12369. if (this.parent === ancestor) {
  12370. return true;
  12371. }
  12372. return this.parent.isDescendantOf(ancestor);
  12373. }
  12374. return false;
  12375. };
  12376. /**
  12377. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12378. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12379. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  12380. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12381. */
  12382. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12383. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12384. if (!this._children) {
  12385. return;
  12386. }
  12387. for (var index = 0; index < this._children.length; index++) {
  12388. var item = this._children[index];
  12389. if (!predicate || predicate(item)) {
  12390. results.push(item);
  12391. }
  12392. if (!directDescendantsOnly) {
  12393. item._getDescendants(results, false, predicate);
  12394. }
  12395. }
  12396. };
  12397. /**
  12398. * Will return all nodes that have this node as ascendant.
  12399. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  12400. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12401. * @return {BABYLON.Node[]} all children nodes of all types.
  12402. */
  12403. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12404. var results = new Array();
  12405. this._getDescendants(results, directDescendantsOnly, predicate);
  12406. return results;
  12407. };
  12408. /**
  12409. * Get all child-meshes of this node.
  12410. */
  12411. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12412. var results = [];
  12413. this._getDescendants(results, directDecendantsOnly, function (node) {
  12414. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12415. });
  12416. return results;
  12417. };
  12418. /**
  12419. * Get all direct children of this node.
  12420. */
  12421. Node.prototype.getChildren = function (predicate) {
  12422. return this.getDescendants(true, predicate);
  12423. };
  12424. Node.prototype._setReady = function (state) {
  12425. if (state === this._isReady) {
  12426. return;
  12427. }
  12428. if (!state) {
  12429. this._isReady = false;
  12430. return;
  12431. }
  12432. this._isReady = true;
  12433. if (this.onReady) {
  12434. this.onReady(this);
  12435. }
  12436. };
  12437. Node.prototype.getAnimationByName = function (name) {
  12438. for (var i = 0; i < this.animations.length; i++) {
  12439. var animation = this.animations[i];
  12440. if (animation.name === name) {
  12441. return animation;
  12442. }
  12443. }
  12444. return null;
  12445. };
  12446. Node.prototype.createAnimationRange = function (name, from, to) {
  12447. // check name not already in use
  12448. if (!this._ranges[name]) {
  12449. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12450. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12451. if (this.animations[i]) {
  12452. this.animations[i].createRange(name, from, to);
  12453. }
  12454. }
  12455. }
  12456. };
  12457. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12458. if (deleteFrames === void 0) { deleteFrames = true; }
  12459. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12460. if (this.animations[i]) {
  12461. this.animations[i].deleteRange(name, deleteFrames);
  12462. }
  12463. }
  12464. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12465. };
  12466. Node.prototype.getAnimationRange = function (name) {
  12467. return this._ranges[name];
  12468. };
  12469. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12470. var range = this.getAnimationRange(name);
  12471. if (!range) {
  12472. return;
  12473. }
  12474. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12475. };
  12476. Node.prototype.serializeAnimationRanges = function () {
  12477. var serializationRanges = [];
  12478. for (var name in this._ranges) {
  12479. var localRange = this._ranges[name];
  12480. if (!localRange) {
  12481. continue;
  12482. }
  12483. var range = {};
  12484. range.name = name;
  12485. range.from = localRange.from;
  12486. range.to = localRange.to;
  12487. serializationRanges.push(range);
  12488. }
  12489. return serializationRanges;
  12490. };
  12491. Node.prototype.dispose = function () {
  12492. this.parent = null;
  12493. // Callback
  12494. this.onDisposeObservable.notifyObservers(this);
  12495. this.onDisposeObservable.clear();
  12496. // Behaviors
  12497. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12498. var behavior = _a[_i];
  12499. behavior.detach();
  12500. }
  12501. this._behaviors = [];
  12502. };
  12503. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12504. if (parsedNode.ranges) {
  12505. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12506. var data = parsedNode.ranges[index];
  12507. node.createAnimationRange(data.name, data.from, data.to);
  12508. }
  12509. }
  12510. };
  12511. __decorate([
  12512. BABYLON.serialize()
  12513. ], Node.prototype, "name", void 0);
  12514. __decorate([
  12515. BABYLON.serialize()
  12516. ], Node.prototype, "id", void 0);
  12517. __decorate([
  12518. BABYLON.serialize()
  12519. ], Node.prototype, "uniqueId", void 0);
  12520. __decorate([
  12521. BABYLON.serialize()
  12522. ], Node.prototype, "state", void 0);
  12523. __decorate([
  12524. BABYLON.serialize()
  12525. ], Node.prototype, "metadata", void 0);
  12526. return Node;
  12527. }());
  12528. BABYLON.Node = Node;
  12529. })(BABYLON || (BABYLON = {}));
  12530. //# sourceMappingURL=babylon.node.js.map
  12531. var BABYLON;
  12532. (function (BABYLON) {
  12533. var BoundingSphere = /** @class */ (function () {
  12534. function BoundingSphere(minimum, maximum) {
  12535. this.minimum = minimum;
  12536. this.maximum = maximum;
  12537. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12538. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12539. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12540. this.radius = distance * 0.5;
  12541. this.centerWorld = BABYLON.Vector3.Zero();
  12542. this._update(BABYLON.Matrix.Identity());
  12543. }
  12544. // Methods
  12545. BoundingSphere.prototype._update = function (world) {
  12546. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12547. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12548. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12549. };
  12550. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12551. for (var i = 0; i < 6; i++) {
  12552. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12553. return false;
  12554. }
  12555. return true;
  12556. };
  12557. BoundingSphere.prototype.intersectsPoint = function (point) {
  12558. var x = this.centerWorld.x - point.x;
  12559. var y = this.centerWorld.y - point.y;
  12560. var z = this.centerWorld.z - point.z;
  12561. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12562. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12563. return false;
  12564. return true;
  12565. };
  12566. // Statics
  12567. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12568. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12569. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12570. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12571. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12572. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12573. return false;
  12574. return true;
  12575. };
  12576. return BoundingSphere;
  12577. }());
  12578. BABYLON.BoundingSphere = BoundingSphere;
  12579. })(BABYLON || (BABYLON = {}));
  12580. //# sourceMappingURL=babylon.boundingSphere.js.map
  12581. var BABYLON;
  12582. (function (BABYLON) {
  12583. var BoundingBox = /** @class */ (function () {
  12584. function BoundingBox(minimum, maximum) {
  12585. this.minimum = minimum;
  12586. this.maximum = maximum;
  12587. this.vectors = new Array();
  12588. this.vectorsWorld = new Array();
  12589. // Bounding vectors
  12590. this.vectors.push(this.minimum.clone());
  12591. this.vectors.push(this.maximum.clone());
  12592. this.vectors.push(this.minimum.clone());
  12593. this.vectors[2].x = this.maximum.x;
  12594. this.vectors.push(this.minimum.clone());
  12595. this.vectors[3].y = this.maximum.y;
  12596. this.vectors.push(this.minimum.clone());
  12597. this.vectors[4].z = this.maximum.z;
  12598. this.vectors.push(this.maximum.clone());
  12599. this.vectors[5].z = this.minimum.z;
  12600. this.vectors.push(this.maximum.clone());
  12601. this.vectors[6].x = this.minimum.x;
  12602. this.vectors.push(this.maximum.clone());
  12603. this.vectors[7].y = this.minimum.y;
  12604. // OBB
  12605. this.center = this.maximum.add(this.minimum).scale(0.5);
  12606. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12607. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12608. // World
  12609. for (var index = 0; index < this.vectors.length; index++) {
  12610. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12611. }
  12612. this.minimumWorld = BABYLON.Vector3.Zero();
  12613. this.maximumWorld = BABYLON.Vector3.Zero();
  12614. this.centerWorld = BABYLON.Vector3.Zero();
  12615. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12616. this._update(BABYLON.Matrix.Identity());
  12617. }
  12618. // Methods
  12619. BoundingBox.prototype.getWorldMatrix = function () {
  12620. return this._worldMatrix;
  12621. };
  12622. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12623. this._worldMatrix.copyFrom(matrix);
  12624. return this;
  12625. };
  12626. BoundingBox.prototype._update = function (world) {
  12627. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12628. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12629. for (var index = 0; index < this.vectors.length; index++) {
  12630. var v = this.vectorsWorld[index];
  12631. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12632. if (v.x < this.minimumWorld.x)
  12633. this.minimumWorld.x = v.x;
  12634. if (v.y < this.minimumWorld.y)
  12635. this.minimumWorld.y = v.y;
  12636. if (v.z < this.minimumWorld.z)
  12637. this.minimumWorld.z = v.z;
  12638. if (v.x > this.maximumWorld.x)
  12639. this.maximumWorld.x = v.x;
  12640. if (v.y > this.maximumWorld.y)
  12641. this.maximumWorld.y = v.y;
  12642. if (v.z > this.maximumWorld.z)
  12643. this.maximumWorld.z = v.z;
  12644. }
  12645. // Extend
  12646. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12647. this.extendSizeWorld.scaleInPlace(0.5);
  12648. // OBB
  12649. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12650. this.centerWorld.scaleInPlace(0.5);
  12651. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12652. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12653. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12654. this._worldMatrix = world;
  12655. };
  12656. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12657. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12658. };
  12659. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12660. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12661. };
  12662. BoundingBox.prototype.intersectsPoint = function (point) {
  12663. var delta = -BABYLON.Epsilon;
  12664. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12665. return false;
  12666. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12667. return false;
  12668. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12669. return false;
  12670. return true;
  12671. };
  12672. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12673. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12674. };
  12675. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12676. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12677. return false;
  12678. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12679. return false;
  12680. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12681. return false;
  12682. return true;
  12683. };
  12684. // Statics
  12685. BoundingBox.Intersects = function (box0, box1) {
  12686. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12687. return false;
  12688. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12689. return false;
  12690. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12691. return false;
  12692. return true;
  12693. };
  12694. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12695. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12696. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12697. return (num <= (sphereRadius * sphereRadius));
  12698. };
  12699. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12700. for (var p = 0; p < 6; p++) {
  12701. for (var i = 0; i < 8; i++) {
  12702. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12703. return false;
  12704. }
  12705. }
  12706. }
  12707. return true;
  12708. };
  12709. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12710. for (var p = 0; p < 6; p++) {
  12711. var inCount = 8;
  12712. for (var i = 0; i < 8; i++) {
  12713. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12714. --inCount;
  12715. }
  12716. else {
  12717. break;
  12718. }
  12719. }
  12720. if (inCount === 0)
  12721. return false;
  12722. }
  12723. return true;
  12724. };
  12725. return BoundingBox;
  12726. }());
  12727. BABYLON.BoundingBox = BoundingBox;
  12728. })(BABYLON || (BABYLON = {}));
  12729. //# sourceMappingURL=babylon.boundingBox.js.map
  12730. var BABYLON;
  12731. (function (BABYLON) {
  12732. var computeBoxExtents = function (axis, box) {
  12733. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12734. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12735. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12736. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12737. var r = r0 + r1 + r2;
  12738. return {
  12739. min: p - r,
  12740. max: p + r
  12741. };
  12742. };
  12743. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12744. var axisOverlap = function (axis, box0, box1) {
  12745. var result0 = computeBoxExtents(axis, box0);
  12746. var result1 = computeBoxExtents(axis, box1);
  12747. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12748. };
  12749. var BoundingInfo = /** @class */ (function () {
  12750. function BoundingInfo(minimum, maximum) {
  12751. this.minimum = minimum;
  12752. this.maximum = maximum;
  12753. this._isLocked = false;
  12754. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12755. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12756. }
  12757. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12758. get: function () {
  12759. return this._isLocked;
  12760. },
  12761. set: function (value) {
  12762. this._isLocked = value;
  12763. },
  12764. enumerable: true,
  12765. configurable: true
  12766. });
  12767. // Methods
  12768. BoundingInfo.prototype.update = function (world) {
  12769. if (this._isLocked) {
  12770. return;
  12771. }
  12772. this.boundingBox._update(world);
  12773. this.boundingSphere._update(world);
  12774. };
  12775. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12776. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12777. return false;
  12778. return this.boundingBox.isInFrustum(frustumPlanes);
  12779. };
  12780. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12781. /**
  12782. * Gets the world distance between the min and max points of the bounding box
  12783. */
  12784. get: function () {
  12785. var boundingBox = this.boundingBox;
  12786. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12787. return size.length();
  12788. },
  12789. enumerable: true,
  12790. configurable: true
  12791. });
  12792. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12793. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12794. };
  12795. BoundingInfo.prototype._checkCollision = function (collider) {
  12796. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12797. };
  12798. BoundingInfo.prototype.intersectsPoint = function (point) {
  12799. if (!this.boundingSphere.centerWorld) {
  12800. return false;
  12801. }
  12802. if (!this.boundingSphere.intersectsPoint(point)) {
  12803. return false;
  12804. }
  12805. if (!this.boundingBox.intersectsPoint(point)) {
  12806. return false;
  12807. }
  12808. return true;
  12809. };
  12810. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12811. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12812. return false;
  12813. }
  12814. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12815. return false;
  12816. }
  12817. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12818. return false;
  12819. }
  12820. if (!precise) {
  12821. return true;
  12822. }
  12823. var box0 = this.boundingBox;
  12824. var box1 = boundingInfo.boundingBox;
  12825. if (!axisOverlap(box0.directions[0], box0, box1))
  12826. return false;
  12827. if (!axisOverlap(box0.directions[1], box0, box1))
  12828. return false;
  12829. if (!axisOverlap(box0.directions[2], box0, box1))
  12830. return false;
  12831. if (!axisOverlap(box1.directions[0], box0, box1))
  12832. return false;
  12833. if (!axisOverlap(box1.directions[1], box0, box1))
  12834. return false;
  12835. if (!axisOverlap(box1.directions[2], box0, box1))
  12836. return false;
  12837. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12838. return false;
  12839. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12840. return false;
  12841. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12842. return false;
  12843. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12844. return false;
  12845. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12846. return false;
  12847. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12848. return false;
  12849. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12850. return false;
  12851. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12852. return false;
  12853. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12854. return false;
  12855. return true;
  12856. };
  12857. return BoundingInfo;
  12858. }());
  12859. BABYLON.BoundingInfo = BoundingInfo;
  12860. })(BABYLON || (BABYLON = {}));
  12861. //# sourceMappingURL=babylon.boundingInfo.js.map
  12862. var BABYLON;
  12863. (function (BABYLON) {
  12864. var AbstractMesh = /** @class */ (function (_super) {
  12865. __extends(AbstractMesh, _super);
  12866. // Constructor
  12867. function AbstractMesh(name, scene) {
  12868. if (scene === void 0) { scene = null; }
  12869. var _this = _super.call(this, name, scene) || this;
  12870. _this._facetNb = 0; // facet number
  12871. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12872. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12873. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12874. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12875. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12876. _this._subDiv = {
  12877. max: 1,
  12878. X: 1,
  12879. Y: 1,
  12880. Z: 1
  12881. };
  12882. // Normal matrix
  12883. _this._nonUniformScaling = false;
  12884. // Events
  12885. /**
  12886. * An event triggered when this mesh collides with another one
  12887. * @type {BABYLON.Observable}
  12888. */
  12889. _this.onCollideObservable = new BABYLON.Observable();
  12890. /**
  12891. * An event triggered when the collision's position changes
  12892. * @type {BABYLON.Observable}
  12893. */
  12894. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12895. /**
  12896. * An event triggered after the world matrix is updated
  12897. * @type {BABYLON.Observable}
  12898. */
  12899. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12900. /**
  12901. * An event triggered when material is changed
  12902. * @type {BABYLON.Observable}
  12903. */
  12904. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12905. // Properties
  12906. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12907. _this.position = BABYLON.Vector3.Zero();
  12908. /**
  12909. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12910. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12911. * or
  12912. * 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.
  12913. * for more info check WebGl documentations
  12914. */
  12915. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12916. /**
  12917. * 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:
  12918. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12919. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12920. * 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.
  12921. */
  12922. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12923. /**
  12924. * 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.
  12925. * The default value is -1 which means don't break the query and wait till the result.
  12926. */
  12927. _this.occlusionRetryCount = -1;
  12928. _this._occlusionInternalRetryCounter = 0;
  12929. _this._isOccluded = false;
  12930. _this._isOcclusionQueryInProgress = false;
  12931. _this._rotation = BABYLON.Vector3.Zero();
  12932. _this._scaling = BABYLON.Vector3.One();
  12933. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12934. _this.visibility = 1.0;
  12935. _this.alphaIndex = Number.MAX_VALUE;
  12936. _this.infiniteDistance = false;
  12937. _this.isVisible = true;
  12938. _this.isPickable = true;
  12939. _this.showBoundingBox = false;
  12940. _this.showSubMeshesBoundingBox = false;
  12941. _this.isBlocker = false;
  12942. _this.enablePointerMoveEvents = false;
  12943. _this.renderingGroupId = 0;
  12944. _this._receiveShadows = false;
  12945. _this.renderOutline = false;
  12946. _this.outlineColor = BABYLON.Color3.Red();
  12947. _this.outlineWidth = 0.02;
  12948. _this.renderOverlay = false;
  12949. _this.overlayColor = BABYLON.Color3.Red();
  12950. _this.overlayAlpha = 0.5;
  12951. _this._hasVertexAlpha = false;
  12952. _this._useVertexColors = true;
  12953. _this._computeBonesUsingShaders = true;
  12954. _this._numBoneInfluencers = 4;
  12955. _this._applyFog = true;
  12956. _this.scalingDeterminant = 1;
  12957. _this.useOctreeForRenderingSelection = true;
  12958. _this.useOctreeForPicking = true;
  12959. _this.useOctreeForCollisions = true;
  12960. _this._layerMask = 0x0FFFFFFF;
  12961. /**
  12962. * True if the mesh must be rendered in any case.
  12963. */
  12964. _this.alwaysSelectAsActiveMesh = false;
  12965. // Collisions
  12966. _this._checkCollisions = false;
  12967. _this._collisionMask = -1;
  12968. _this._collisionGroup = -1;
  12969. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12970. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12971. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12972. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12973. // Edges
  12974. _this.edgesWidth = 1;
  12975. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12976. // Cache
  12977. _this._localWorld = BABYLON.Matrix.Zero();
  12978. _this._worldMatrix = BABYLON.Matrix.Zero();
  12979. _this._absolutePosition = BABYLON.Vector3.Zero();
  12980. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12981. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12982. _this._isDirty = false;
  12983. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12984. _this._postMultiplyPivotMatrix = false;
  12985. _this._isDisposed = false;
  12986. _this._renderId = 0;
  12987. _this._intersectionsInProgress = new Array();
  12988. _this._isWorldMatrixFrozen = false;
  12989. _this._unIndexed = false;
  12990. _this._lightSources = new Array();
  12991. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12992. if (collidedMesh === void 0) { collidedMesh = null; }
  12993. //TODO move this to the collision coordinator!
  12994. if (_this.getScene().workerCollisions)
  12995. newPosition.multiplyInPlace(_this._collider.radius);
  12996. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12997. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12998. _this.position.addInPlace(_this._diffPositionForCollisions);
  12999. }
  13000. if (collidedMesh) {
  13001. _this.onCollideObservable.notifyObservers(collidedMesh);
  13002. }
  13003. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  13004. };
  13005. _this.getScene().addMesh(_this);
  13006. _this._resyncLightSources();
  13007. return _this;
  13008. }
  13009. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  13010. get: function () {
  13011. return AbstractMesh._BILLBOARDMODE_NONE;
  13012. },
  13013. enumerable: true,
  13014. configurable: true
  13015. });
  13016. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  13017. get: function () {
  13018. return AbstractMesh._BILLBOARDMODE_X;
  13019. },
  13020. enumerable: true,
  13021. configurable: true
  13022. });
  13023. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  13024. get: function () {
  13025. return AbstractMesh._BILLBOARDMODE_Y;
  13026. },
  13027. enumerable: true,
  13028. configurable: true
  13029. });
  13030. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  13031. get: function () {
  13032. return AbstractMesh._BILLBOARDMODE_Z;
  13033. },
  13034. enumerable: true,
  13035. configurable: true
  13036. });
  13037. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  13038. get: function () {
  13039. return AbstractMesh._BILLBOARDMODE_ALL;
  13040. },
  13041. enumerable: true,
  13042. configurable: true
  13043. });
  13044. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  13045. /**
  13046. * Read-only : the number of facets in the mesh
  13047. */
  13048. get: function () {
  13049. return this._facetNb;
  13050. },
  13051. enumerable: true,
  13052. configurable: true
  13053. });
  13054. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  13055. /**
  13056. * The number (integer) of subdivisions per axis in the partioning space
  13057. */
  13058. get: function () {
  13059. return this._partitioningSubdivisions;
  13060. },
  13061. set: function (nb) {
  13062. this._partitioningSubdivisions = nb;
  13063. },
  13064. enumerable: true,
  13065. configurable: true
  13066. });
  13067. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  13068. /**
  13069. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  13070. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  13071. */
  13072. get: function () {
  13073. return this._partitioningBBoxRatio;
  13074. },
  13075. set: function (ratio) {
  13076. this._partitioningBBoxRatio = ratio;
  13077. },
  13078. enumerable: true,
  13079. configurable: true
  13080. });
  13081. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  13082. /**
  13083. * Read-only boolean : is the feature facetData enabled ?
  13084. */
  13085. get: function () {
  13086. return this._facetDataEnabled;
  13087. },
  13088. enumerable: true,
  13089. configurable: true
  13090. });
  13091. Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", {
  13092. get: function () {
  13093. return this._nonUniformScaling;
  13094. },
  13095. set: function (value) {
  13096. if (this._nonUniformScaling === value) {
  13097. return;
  13098. }
  13099. this._nonUniformScaling = true;
  13100. this._markSubMeshesAsMiscDirty();
  13101. },
  13102. enumerable: true,
  13103. configurable: true
  13104. });
  13105. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  13106. set: function (callback) {
  13107. if (this._onCollideObserver) {
  13108. this.onCollideObservable.remove(this._onCollideObserver);
  13109. }
  13110. this._onCollideObserver = this.onCollideObservable.add(callback);
  13111. },
  13112. enumerable: true,
  13113. configurable: true
  13114. });
  13115. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  13116. set: function (callback) {
  13117. if (this._onCollisionPositionChangeObserver) {
  13118. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  13119. }
  13120. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  13121. },
  13122. enumerable: true,
  13123. configurable: true
  13124. });
  13125. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  13126. /**
  13127. * 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.
  13128. */
  13129. get: function () {
  13130. return this._isOccluded;
  13131. },
  13132. set: function (value) {
  13133. this._isOccluded = value;
  13134. },
  13135. enumerable: true,
  13136. configurable: true
  13137. });
  13138. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  13139. /**
  13140. * Flag to check the progress status of the query
  13141. */
  13142. get: function () {
  13143. return this._isOcclusionQueryInProgress;
  13144. },
  13145. enumerable: true,
  13146. configurable: true
  13147. });
  13148. Object.defineProperty(AbstractMesh.prototype, "material", {
  13149. get: function () {
  13150. return this._material;
  13151. },
  13152. set: function (value) {
  13153. if (this._material === value) {
  13154. return;
  13155. }
  13156. this._material = value;
  13157. if (this.onMaterialChangedObservable.hasObservers) {
  13158. this.onMaterialChangedObservable.notifyObservers(this);
  13159. }
  13160. if (!this.subMeshes) {
  13161. return;
  13162. }
  13163. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13164. var subMesh = _a[_i];
  13165. subMesh.setEffect(null);
  13166. }
  13167. },
  13168. enumerable: true,
  13169. configurable: true
  13170. });
  13171. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  13172. get: function () {
  13173. return this._receiveShadows;
  13174. },
  13175. set: function (value) {
  13176. if (this._receiveShadows === value) {
  13177. return;
  13178. }
  13179. this._receiveShadows = value;
  13180. this._markSubMeshesAsLightDirty();
  13181. },
  13182. enumerable: true,
  13183. configurable: true
  13184. });
  13185. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  13186. get: function () {
  13187. return this._hasVertexAlpha;
  13188. },
  13189. set: function (value) {
  13190. if (this._hasVertexAlpha === value) {
  13191. return;
  13192. }
  13193. this._hasVertexAlpha = value;
  13194. this._markSubMeshesAsAttributesDirty();
  13195. },
  13196. enumerable: true,
  13197. configurable: true
  13198. });
  13199. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  13200. get: function () {
  13201. return this._useVertexColors;
  13202. },
  13203. set: function (value) {
  13204. if (this._useVertexColors === value) {
  13205. return;
  13206. }
  13207. this._useVertexColors = value;
  13208. this._markSubMeshesAsAttributesDirty();
  13209. },
  13210. enumerable: true,
  13211. configurable: true
  13212. });
  13213. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  13214. get: function () {
  13215. return this._computeBonesUsingShaders;
  13216. },
  13217. set: function (value) {
  13218. if (this._computeBonesUsingShaders === value) {
  13219. return;
  13220. }
  13221. this._computeBonesUsingShaders = value;
  13222. this._markSubMeshesAsAttributesDirty();
  13223. },
  13224. enumerable: true,
  13225. configurable: true
  13226. });
  13227. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  13228. get: function () {
  13229. return this._numBoneInfluencers;
  13230. },
  13231. set: function (value) {
  13232. if (this._numBoneInfluencers === value) {
  13233. return;
  13234. }
  13235. this._numBoneInfluencers = value;
  13236. this._markSubMeshesAsAttributesDirty();
  13237. },
  13238. enumerable: true,
  13239. configurable: true
  13240. });
  13241. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  13242. get: function () {
  13243. return this._applyFog;
  13244. },
  13245. set: function (value) {
  13246. if (this._applyFog === value) {
  13247. return;
  13248. }
  13249. this._applyFog = value;
  13250. this._markSubMeshesAsMiscDirty();
  13251. },
  13252. enumerable: true,
  13253. configurable: true
  13254. });
  13255. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  13256. get: function () {
  13257. return this._layerMask;
  13258. },
  13259. set: function (value) {
  13260. if (value === this._layerMask) {
  13261. return;
  13262. }
  13263. this._layerMask = value;
  13264. this._resyncLightSources();
  13265. },
  13266. enumerable: true,
  13267. configurable: true
  13268. });
  13269. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  13270. get: function () {
  13271. return this._collisionMask;
  13272. },
  13273. set: function (mask) {
  13274. this._collisionMask = !isNaN(mask) ? mask : -1;
  13275. },
  13276. enumerable: true,
  13277. configurable: true
  13278. });
  13279. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  13280. get: function () {
  13281. return this._collisionGroup;
  13282. },
  13283. set: function (mask) {
  13284. this._collisionGroup = !isNaN(mask) ? mask : -1;
  13285. },
  13286. enumerable: true,
  13287. configurable: true
  13288. });
  13289. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  13290. get: function () {
  13291. return null;
  13292. },
  13293. enumerable: true,
  13294. configurable: true
  13295. });
  13296. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  13297. get: function () {
  13298. return this._skeleton;
  13299. },
  13300. set: function (value) {
  13301. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  13302. this._skeleton._unregisterMeshWithPoseMatrix(this);
  13303. }
  13304. if (value && value.needInitialSkinMatrix) {
  13305. value._registerMeshWithPoseMatrix(this);
  13306. }
  13307. this._skeleton = value;
  13308. if (!this._skeleton) {
  13309. this._bonesTransformMatrices = null;
  13310. }
  13311. this._markSubMeshesAsAttributesDirty();
  13312. },
  13313. enumerable: true,
  13314. configurable: true
  13315. });
  13316. /**
  13317. * Boolean : true if the mesh has been disposed.
  13318. */
  13319. AbstractMesh.prototype.isDisposed = function () {
  13320. return this._isDisposed;
  13321. };
  13322. /**
  13323. * Returns the string "AbstractMesh"
  13324. */
  13325. AbstractMesh.prototype.getClassName = function () {
  13326. return "AbstractMesh";
  13327. };
  13328. /**
  13329. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13330. */
  13331. AbstractMesh.prototype.toString = function (fullDetails) {
  13332. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  13333. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  13334. if (this._skeleton) {
  13335. ret += ", skeleton: " + this._skeleton.name;
  13336. }
  13337. if (fullDetails) {
  13338. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  13339. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  13340. }
  13341. return ret;
  13342. };
  13343. AbstractMesh.prototype._rebuild = function () {
  13344. if (this._occlusionQuery) {
  13345. this._occlusionQuery = null;
  13346. }
  13347. if (this._edgesRenderer) {
  13348. this._edgesRenderer._rebuild();
  13349. }
  13350. if (!this.subMeshes) {
  13351. return;
  13352. }
  13353. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13354. var subMesh = _a[_i];
  13355. subMesh._rebuild();
  13356. }
  13357. };
  13358. AbstractMesh.prototype._resyncLightSources = function () {
  13359. this._lightSources.length = 0;
  13360. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  13361. var light = _a[_i];
  13362. if (!light.isEnabled()) {
  13363. continue;
  13364. }
  13365. if (light.canAffectMesh(this)) {
  13366. this._lightSources.push(light);
  13367. }
  13368. }
  13369. this._markSubMeshesAsLightDirty();
  13370. };
  13371. AbstractMesh.prototype._resyncLighSource = function (light) {
  13372. var isIn = light.isEnabled() && light.canAffectMesh(this);
  13373. var index = this._lightSources.indexOf(light);
  13374. if (index === -1) {
  13375. if (!isIn) {
  13376. return;
  13377. }
  13378. this._lightSources.push(light);
  13379. }
  13380. else {
  13381. if (isIn) {
  13382. return;
  13383. }
  13384. this._lightSources.splice(index, 1);
  13385. }
  13386. this._markSubMeshesAsLightDirty();
  13387. };
  13388. AbstractMesh.prototype._removeLightSource = function (light) {
  13389. var index = this._lightSources.indexOf(light);
  13390. if (index === -1) {
  13391. return;
  13392. }
  13393. this._lightSources.splice(index, 1);
  13394. };
  13395. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  13396. if (!this.subMeshes) {
  13397. return;
  13398. }
  13399. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13400. var subMesh = _a[_i];
  13401. if (subMesh._materialDefines) {
  13402. func(subMesh._materialDefines);
  13403. }
  13404. }
  13405. };
  13406. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  13407. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  13408. };
  13409. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  13410. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  13411. };
  13412. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  13413. if (!this.subMeshes) {
  13414. return;
  13415. }
  13416. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13417. var subMesh = _a[_i];
  13418. var material = subMesh.getMaterial();
  13419. if (material) {
  13420. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  13421. }
  13422. }
  13423. };
  13424. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  13425. /**
  13426. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13427. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13428. * Default : (0.0, 0.0, 0.0)
  13429. */
  13430. get: function () {
  13431. return this._rotation;
  13432. },
  13433. set: function (newRotation) {
  13434. this._rotation = newRotation;
  13435. },
  13436. enumerable: true,
  13437. configurable: true
  13438. });
  13439. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  13440. /**
  13441. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13442. * Default : (1.0, 1.0, 1.0)
  13443. */
  13444. get: function () {
  13445. return this._scaling;
  13446. },
  13447. set: function (newScaling) {
  13448. this._scaling = newScaling;
  13449. if (this.physicsImpostor) {
  13450. this.physicsImpostor.forceUpdate();
  13451. }
  13452. },
  13453. enumerable: true,
  13454. configurable: true
  13455. });
  13456. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  13457. /**
  13458. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13459. * It's null by default.
  13460. * 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)
  13461. */
  13462. get: function () {
  13463. return this._rotationQuaternion;
  13464. },
  13465. set: function (quaternion) {
  13466. this._rotationQuaternion = quaternion;
  13467. //reset the rotation vector.
  13468. if (quaternion && this.rotation.length()) {
  13469. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13470. }
  13471. },
  13472. enumerable: true,
  13473. configurable: true
  13474. });
  13475. // Methods
  13476. /**
  13477. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13478. * Returns the AbstractMesh.
  13479. */
  13480. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  13481. this._poseMatrix.copyFrom(matrix);
  13482. return this;
  13483. };
  13484. /**
  13485. * Returns the mesh Pose matrix.
  13486. * Returned object : Matrix
  13487. */
  13488. AbstractMesh.prototype.getPoseMatrix = function () {
  13489. return this._poseMatrix;
  13490. };
  13491. /**
  13492. * Disables the mesh edger rendering mode.
  13493. * Returns the AbstractMesh.
  13494. */
  13495. AbstractMesh.prototype.disableEdgesRendering = function () {
  13496. if (this._edgesRenderer) {
  13497. this._edgesRenderer.dispose();
  13498. this._edgesRenderer = null;
  13499. }
  13500. return this;
  13501. };
  13502. /**
  13503. * Enables the edge rendering mode on the mesh.
  13504. * This mode makes the mesh edges visible.
  13505. * Returns the AbstractMesh.
  13506. */
  13507. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  13508. if (epsilon === void 0) { epsilon = 0.95; }
  13509. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13510. this.disableEdgesRendering();
  13511. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13512. return this;
  13513. };
  13514. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13515. /**
  13516. * Returns true if the mesh is blocked. Used by the class Mesh.
  13517. * Returns the boolean `false` by default.
  13518. */
  13519. get: function () {
  13520. return false;
  13521. },
  13522. enumerable: true,
  13523. configurable: true
  13524. });
  13525. /**
  13526. * Returns the mesh itself by default, used by the class Mesh.
  13527. * Returned type : AbstractMesh
  13528. */
  13529. AbstractMesh.prototype.getLOD = function (camera) {
  13530. return this;
  13531. };
  13532. /**
  13533. * Returns 0 by default, used by the class Mesh.
  13534. * Returns an integer.
  13535. */
  13536. AbstractMesh.prototype.getTotalVertices = function () {
  13537. return 0;
  13538. };
  13539. /**
  13540. * Returns null by default, used by the class Mesh.
  13541. * Returned type : integer array
  13542. */
  13543. AbstractMesh.prototype.getIndices = function () {
  13544. return null;
  13545. };
  13546. /**
  13547. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13548. * Returned type : float array or Float32Array
  13549. */
  13550. AbstractMesh.prototype.getVerticesData = function (kind) {
  13551. return null;
  13552. };
  13553. /**
  13554. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13555. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13556. * The `data` are either a numeric array either a Float32Array.
  13557. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13558. * 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).
  13559. * Note that a new underlying VertexBuffer object is created each call.
  13560. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13561. *
  13562. * Possible `kind` values :
  13563. * - BABYLON.VertexBuffer.PositionKind
  13564. * - BABYLON.VertexBuffer.UVKind
  13565. * - BABYLON.VertexBuffer.UV2Kind
  13566. * - BABYLON.VertexBuffer.UV3Kind
  13567. * - BABYLON.VertexBuffer.UV4Kind
  13568. * - BABYLON.VertexBuffer.UV5Kind
  13569. * - BABYLON.VertexBuffer.UV6Kind
  13570. * - BABYLON.VertexBuffer.ColorKind
  13571. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13572. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13573. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13574. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13575. *
  13576. * Returns the Mesh.
  13577. */
  13578. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13579. return this;
  13580. };
  13581. /**
  13582. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13583. * If the mesh has no geometry, it is simply returned as it is.
  13584. * The `data` are either a numeric array either a Float32Array.
  13585. * No new underlying VertexBuffer object is created.
  13586. * 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.
  13587. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13588. *
  13589. * Possible `kind` values :
  13590. * - BABYLON.VertexBuffer.PositionKind
  13591. * - BABYLON.VertexBuffer.UVKind
  13592. * - BABYLON.VertexBuffer.UV2Kind
  13593. * - BABYLON.VertexBuffer.UV3Kind
  13594. * - BABYLON.VertexBuffer.UV4Kind
  13595. * - BABYLON.VertexBuffer.UV5Kind
  13596. * - BABYLON.VertexBuffer.UV6Kind
  13597. * - BABYLON.VertexBuffer.ColorKind
  13598. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13599. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13600. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13601. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13602. *
  13603. * Returns the Mesh.
  13604. */
  13605. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13606. return this;
  13607. };
  13608. /**
  13609. * Sets the mesh indices.
  13610. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13611. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13612. * This method creates a new index buffer each call.
  13613. * Returns the Mesh.
  13614. */
  13615. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13616. return this;
  13617. };
  13618. /** Returns false by default, used by the class Mesh.
  13619. * Returns a boolean
  13620. */
  13621. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13622. return false;
  13623. };
  13624. /**
  13625. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13626. * Returns a BoundingInfo
  13627. */
  13628. AbstractMesh.prototype.getBoundingInfo = function () {
  13629. if (this._masterMesh) {
  13630. return this._masterMesh.getBoundingInfo();
  13631. }
  13632. if (!this._boundingInfo) {
  13633. this._updateBoundingInfo();
  13634. }
  13635. return this._boundingInfo;
  13636. };
  13637. /**
  13638. * Sets a mesh new object BoundingInfo.
  13639. * Returns the AbstractMesh.
  13640. */
  13641. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13642. this._boundingInfo = boundingInfo;
  13643. return this;
  13644. };
  13645. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13646. get: function () {
  13647. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  13648. },
  13649. enumerable: true,
  13650. configurable: true
  13651. });
  13652. AbstractMesh.prototype._preActivate = function () {
  13653. };
  13654. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13655. };
  13656. AbstractMesh.prototype._activate = function (renderId) {
  13657. this._renderId = renderId;
  13658. };
  13659. /**
  13660. * Returns the last update of the World matrix
  13661. * Returns a Matrix.
  13662. */
  13663. AbstractMesh.prototype.getWorldMatrix = function () {
  13664. if (this._masterMesh) {
  13665. return this._masterMesh.getWorldMatrix();
  13666. }
  13667. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  13668. this.computeWorldMatrix();
  13669. }
  13670. return this._worldMatrix;
  13671. };
  13672. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13673. /**
  13674. * Returns directly the last state of the mesh World matrix.
  13675. * A Matrix is returned.
  13676. */
  13677. get: function () {
  13678. return this._worldMatrix;
  13679. },
  13680. enumerable: true,
  13681. configurable: true
  13682. });
  13683. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13684. /**
  13685. * Returns the current mesh absolute position.
  13686. * Retuns a Vector3.
  13687. */
  13688. get: function () {
  13689. return this._absolutePosition;
  13690. },
  13691. enumerable: true,
  13692. configurable: true
  13693. });
  13694. /**
  13695. * Prevents the World matrix to be computed any longer.
  13696. * Returns the AbstractMesh.
  13697. */
  13698. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13699. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13700. this.computeWorldMatrix(true);
  13701. this._isWorldMatrixFrozen = true;
  13702. return this;
  13703. };
  13704. /**
  13705. * Allows back the World matrix computation.
  13706. * Returns the AbstractMesh.
  13707. */
  13708. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13709. this._isWorldMatrixFrozen = false;
  13710. this.computeWorldMatrix(true);
  13711. return this;
  13712. };
  13713. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13714. /**
  13715. * True if the World matrix has been frozen.
  13716. * Returns a boolean.
  13717. */
  13718. get: function () {
  13719. return this._isWorldMatrixFrozen;
  13720. },
  13721. enumerable: true,
  13722. configurable: true
  13723. });
  13724. /**
  13725. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13726. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13727. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13728. * The passed axis is also normalized.
  13729. * Returns the AbstractMesh.
  13730. */
  13731. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13732. axis.normalize();
  13733. if (!this.rotationQuaternion) {
  13734. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13735. this.rotation = BABYLON.Vector3.Zero();
  13736. }
  13737. var rotationQuaternion;
  13738. if (!space || space === BABYLON.Space.LOCAL) {
  13739. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13740. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13741. }
  13742. else {
  13743. if (this.parent) {
  13744. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13745. invertParentWorldMatrix.invert();
  13746. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13747. }
  13748. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13749. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13750. }
  13751. return this;
  13752. };
  13753. /**
  13754. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13755. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13756. * The passed axis is also normalized.
  13757. * Returns the AbstractMesh.
  13758. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13759. */
  13760. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13761. axis.normalize();
  13762. if (!this.rotationQuaternion) {
  13763. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13764. this.rotation.copyFromFloats(0, 0, 0);
  13765. }
  13766. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13767. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13768. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13769. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13770. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13771. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13772. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13773. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13774. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13775. return this;
  13776. };
  13777. /**
  13778. * Translates the mesh along the axis vector for the passed distance in the given space.
  13779. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13780. * Returns the AbstractMesh.
  13781. */
  13782. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13783. var displacementVector = axis.scale(distance);
  13784. if (!space || space === BABYLON.Space.LOCAL) {
  13785. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13786. this.setPositionWithLocalVector(tempV3);
  13787. }
  13788. else {
  13789. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13790. }
  13791. return this;
  13792. };
  13793. /**
  13794. * Adds a rotation step to the mesh current rotation.
  13795. * x, y, z are Euler angles expressed in radians.
  13796. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13797. * This means this rotation is made in the mesh local space only.
  13798. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13799. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13800. * ```javascript
  13801. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13802. * ```
  13803. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13804. * 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.
  13805. * Returns the AbstractMesh.
  13806. */
  13807. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13808. var rotationQuaternion;
  13809. if (this.rotationQuaternion) {
  13810. rotationQuaternion = this.rotationQuaternion;
  13811. }
  13812. else {
  13813. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13814. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13815. }
  13816. var accumulation = BABYLON.Tmp.Quaternion[0];
  13817. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13818. rotationQuaternion.multiplyInPlace(accumulation);
  13819. if (!this.rotationQuaternion) {
  13820. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13821. }
  13822. return this;
  13823. };
  13824. /**
  13825. * Retuns the mesh absolute position in the World.
  13826. * Returns a Vector3.
  13827. */
  13828. AbstractMesh.prototype.getAbsolutePosition = function () {
  13829. this.computeWorldMatrix();
  13830. return this._absolutePosition;
  13831. };
  13832. /**
  13833. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13834. * Returns the AbstractMesh.
  13835. */
  13836. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13837. if (!absolutePosition) {
  13838. return this;
  13839. }
  13840. var absolutePositionX;
  13841. var absolutePositionY;
  13842. var absolutePositionZ;
  13843. if (absolutePosition.x === undefined) {
  13844. if (arguments.length < 3) {
  13845. return this;
  13846. }
  13847. absolutePositionX = arguments[0];
  13848. absolutePositionY = arguments[1];
  13849. absolutePositionZ = arguments[2];
  13850. }
  13851. else {
  13852. absolutePositionX = absolutePosition.x;
  13853. absolutePositionY = absolutePosition.y;
  13854. absolutePositionZ = absolutePosition.z;
  13855. }
  13856. if (this.parent) {
  13857. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13858. invertParentWorldMatrix.invert();
  13859. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13860. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13861. }
  13862. else {
  13863. this.position.x = absolutePositionX;
  13864. this.position.y = absolutePositionY;
  13865. this.position.z = absolutePositionZ;
  13866. }
  13867. return this;
  13868. };
  13869. // ================================== Point of View Movement =================================
  13870. /**
  13871. * Perform relative position change from the point of view of behind the front of the mesh.
  13872. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13873. * Supports definition of mesh facing forward or backward.
  13874. * @param {number} amountRight
  13875. * @param {number} amountUp
  13876. * @param {number} amountForward
  13877. *
  13878. * Returns the AbstractMesh.
  13879. */
  13880. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13881. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13882. return this;
  13883. };
  13884. /**
  13885. * Calculate relative position change from the point of view of behind the front of the mesh.
  13886. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13887. * Supports definition of mesh facing forward or backward.
  13888. * @param {number} amountRight
  13889. * @param {number} amountUp
  13890. * @param {number} amountForward
  13891. *
  13892. * Returns a new Vector3.
  13893. */
  13894. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13895. var rotMatrix = new BABYLON.Matrix();
  13896. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13897. rotQuaternion.toRotationMatrix(rotMatrix);
  13898. var translationDelta = BABYLON.Vector3.Zero();
  13899. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13900. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13901. return translationDelta;
  13902. };
  13903. // ================================== Point of View Rotation =================================
  13904. /**
  13905. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13906. * Supports definition of mesh facing forward or backward.
  13907. * @param {number} flipBack
  13908. * @param {number} twirlClockwise
  13909. * @param {number} tiltRight
  13910. *
  13911. * Returns the AbstractMesh.
  13912. */
  13913. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13914. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13915. return this;
  13916. };
  13917. /**
  13918. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13919. * Supports definition of mesh facing forward or backward.
  13920. * @param {number} flipBack
  13921. * @param {number} twirlClockwise
  13922. * @param {number} tiltRight
  13923. *
  13924. * Returns a new Vector3.
  13925. */
  13926. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13927. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13928. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13929. };
  13930. /**
  13931. * Sets a new pivot matrix to the mesh.
  13932. * Returns the AbstractMesh.
  13933. */
  13934. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13935. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13936. this._pivotMatrix = matrix.clone();
  13937. this._cache.pivotMatrixUpdated = true;
  13938. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13939. if (this._postMultiplyPivotMatrix) {
  13940. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13941. }
  13942. return this;
  13943. };
  13944. /**
  13945. * Returns the mesh pivot matrix.
  13946. * Default : Identity.
  13947. * A Matrix is returned.
  13948. */
  13949. AbstractMesh.prototype.getPivotMatrix = function () {
  13950. return this._pivotMatrix;
  13951. };
  13952. AbstractMesh.prototype._isSynchronized = function () {
  13953. if (this._isDirty) {
  13954. return false;
  13955. }
  13956. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13957. return false;
  13958. if (this._cache.pivotMatrixUpdated) {
  13959. return false;
  13960. }
  13961. if (this.infiniteDistance) {
  13962. return false;
  13963. }
  13964. if (!this._cache.position.equals(this.position))
  13965. return false;
  13966. if (this.rotationQuaternion) {
  13967. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13968. return false;
  13969. }
  13970. if (!this._cache.rotation.equals(this.rotation))
  13971. return false;
  13972. if (!this._cache.scaling.equals(this.scaling))
  13973. return false;
  13974. return true;
  13975. };
  13976. AbstractMesh.prototype._initCache = function () {
  13977. _super.prototype._initCache.call(this);
  13978. this._cache.localMatrixUpdated = false;
  13979. this._cache.position = BABYLON.Vector3.Zero();
  13980. this._cache.scaling = BABYLON.Vector3.Zero();
  13981. this._cache.rotation = BABYLON.Vector3.Zero();
  13982. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13983. this._cache.billboardMode = -1;
  13984. };
  13985. AbstractMesh.prototype.markAsDirty = function (property) {
  13986. if (property === "rotation") {
  13987. this.rotationQuaternion = null;
  13988. }
  13989. this._currentRenderId = Number.MAX_VALUE;
  13990. this._isDirty = true;
  13991. return this;
  13992. };
  13993. /**
  13994. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13995. */
  13996. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13997. this.computeWorldMatrix(true);
  13998. var min;
  13999. var max;
  14000. var boundingInfo = this.getBoundingInfo();
  14001. if (!this.subMeshes || !boundingInfo) {
  14002. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14003. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14004. }
  14005. else {
  14006. min = boundingInfo.boundingBox.minimumWorld;
  14007. max = boundingInfo.boundingBox.maximumWorld;
  14008. }
  14009. var descendants = this.getDescendants(false);
  14010. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14011. var descendant = descendants_1[_i];
  14012. var childMesh = descendant;
  14013. childMesh.computeWorldMatrix(true);
  14014. var childBoundingInfo = childMesh.getBoundingInfo();
  14015. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  14016. continue;
  14017. }
  14018. var boundingBox = childBoundingInfo.boundingBox;
  14019. var minBox = boundingBox.minimumWorld;
  14020. var maxBox = boundingBox.maximumWorld;
  14021. BABYLON.Tools.CheckExtends(minBox, min, max);
  14022. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14023. }
  14024. return {
  14025. min: min,
  14026. max: max
  14027. };
  14028. };
  14029. /**
  14030. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  14031. * Returns the AbstractMesh.
  14032. */
  14033. AbstractMesh.prototype._updateBoundingInfo = function () {
  14034. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  14035. this._boundingInfo.update(this.worldMatrixFromCache);
  14036. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14037. return this;
  14038. };
  14039. /**
  14040. * Update a mesh's children BoundingInfo objects only.
  14041. * Returns the AbstractMesh.
  14042. */
  14043. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  14044. if (!this.subMeshes) {
  14045. return this;
  14046. }
  14047. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  14048. var subMesh = this.subMeshes[subIndex];
  14049. if (!subMesh.IsGlobal) {
  14050. subMesh.updateBoundingInfo(matrix);
  14051. }
  14052. }
  14053. return this;
  14054. };
  14055. /**
  14056. * Computes the mesh World matrix and returns it.
  14057. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14058. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14059. * If the parameter `force`is set to `true`, the actual computation is done.
  14060. * Returns the mesh World Matrix.
  14061. */
  14062. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  14063. if (this._isWorldMatrixFrozen) {
  14064. return this._worldMatrix;
  14065. }
  14066. if (!force && this.isSynchronized(true)) {
  14067. this._currentRenderId = this.getScene().getRenderId();
  14068. return this._worldMatrix;
  14069. }
  14070. this._cache.position.copyFrom(this.position);
  14071. this._cache.scaling.copyFrom(this.scaling);
  14072. this._cache.pivotMatrixUpdated = false;
  14073. this._cache.billboardMode = this.billboardMode;
  14074. this._currentRenderId = this.getScene().getRenderId();
  14075. this._isDirty = false;
  14076. // Scaling
  14077. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14078. // Rotation
  14079. //rotate, if quaternion is set and rotation was used
  14080. if (this.rotationQuaternion) {
  14081. var len = this.rotation.length();
  14082. if (len) {
  14083. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14084. this.rotation.copyFromFloats(0, 0, 0);
  14085. }
  14086. }
  14087. if (this.rotationQuaternion) {
  14088. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14089. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14090. }
  14091. else {
  14092. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14093. this._cache.rotation.copyFrom(this.rotation);
  14094. }
  14095. // Translation
  14096. var camera = this.getScene().activeCamera;
  14097. if (this.infiniteDistance && !this.parent && camera) {
  14098. var cameraWorldMatrix = camera.getWorldMatrix();
  14099. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14100. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14101. }
  14102. else {
  14103. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14104. }
  14105. // Composing transformations
  14106. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14107. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14108. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14109. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14110. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  14111. // Need to decompose each rotation here
  14112. var currentPosition = BABYLON.Tmp.Vector3[3];
  14113. if (this.parent && this.parent.getWorldMatrix) {
  14114. if (this._meshToBoneReferal) {
  14115. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14116. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14117. }
  14118. else {
  14119. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14120. }
  14121. }
  14122. else {
  14123. currentPosition.copyFrom(this.position);
  14124. }
  14125. currentPosition.subtractInPlace(camera.globalPosition);
  14126. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14127. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  14128. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14129. }
  14130. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  14131. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14132. }
  14133. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  14134. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14135. }
  14136. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14137. }
  14138. else {
  14139. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14140. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14141. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14142. }
  14143. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14144. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14145. }
  14146. // Local world
  14147. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14148. // Parent
  14149. if (this.parent && this.parent.getWorldMatrix) {
  14150. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  14151. if (this._meshToBoneReferal) {
  14152. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14153. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  14154. }
  14155. else {
  14156. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  14157. }
  14158. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  14159. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  14160. this._worldMatrix.copyFrom(this._localWorld);
  14161. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  14162. }
  14163. else {
  14164. if (this._meshToBoneReferal) {
  14165. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14166. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  14167. }
  14168. else {
  14169. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  14170. }
  14171. }
  14172. this._markSyncedWithParent();
  14173. }
  14174. else {
  14175. this._worldMatrix.copyFrom(this._localWorld);
  14176. }
  14177. // Post multiply inverse of pivotMatrix
  14178. if (this._postMultiplyPivotMatrix) {
  14179. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  14180. }
  14181. // Normal matrix
  14182. if (this.scaling.isNonUniform) {
  14183. this.nonUniformScaling = true;
  14184. }
  14185. else if (this.parent && this.parent._nonUniformScaling) {
  14186. this.nonUniformScaling = this.parent._nonUniformScaling;
  14187. }
  14188. else {
  14189. this.nonUniformScaling = false;
  14190. }
  14191. // Bounding info
  14192. this._updateBoundingInfo();
  14193. // Absolute position
  14194. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14195. // Callbacks
  14196. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14197. if (!this._poseMatrix) {
  14198. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14199. }
  14200. return this._worldMatrix;
  14201. };
  14202. /**
  14203. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14204. * @param func: callback function to add
  14205. *
  14206. * Returns the AbstractMesh.
  14207. */
  14208. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14209. this.onAfterWorldMatrixUpdateObservable.add(func);
  14210. return this;
  14211. };
  14212. /**
  14213. * Removes a registered callback function.
  14214. * Returns the AbstractMesh.
  14215. */
  14216. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14217. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14218. return this;
  14219. };
  14220. /**
  14221. * Sets the mesh position in its local space.
  14222. * Returns the AbstractMesh.
  14223. */
  14224. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  14225. this.computeWorldMatrix();
  14226. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14227. return this;
  14228. };
  14229. /**
  14230. * Returns the mesh position in the local space from the current World matrix values.
  14231. * Returns a new Vector3.
  14232. */
  14233. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  14234. this.computeWorldMatrix();
  14235. var invLocalWorldMatrix = this._localWorld.clone();
  14236. invLocalWorldMatrix.invert();
  14237. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14238. };
  14239. /**
  14240. * Translates the mesh along the passed Vector3 in its local space.
  14241. * Returns the AbstractMesh.
  14242. */
  14243. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  14244. this.computeWorldMatrix(true);
  14245. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14246. return this;
  14247. };
  14248. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14249. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  14250. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  14251. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  14252. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  14253. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  14254. /// <returns>Mesh oriented towards targetMesh</returns>
  14255. if (yawCor === void 0) { yawCor = 0; }
  14256. if (pitchCor === void 0) { pitchCor = 0; }
  14257. if (rollCor === void 0) { rollCor = 0; }
  14258. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14259. var dv = AbstractMesh._lookAtVectorCache;
  14260. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14261. targetPoint.subtractToRef(pos, dv);
  14262. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14263. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14264. var pitch = Math.atan2(dv.y, len);
  14265. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  14266. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14267. return this;
  14268. };
  14269. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  14270. this._meshToBoneReferal = affectedMesh;
  14271. this.parent = bone;
  14272. if (bone.getWorldMatrix().determinant() < 0) {
  14273. this.scalingDeterminant *= -1;
  14274. }
  14275. return this;
  14276. };
  14277. AbstractMesh.prototype.detachFromBone = function () {
  14278. if (!this.parent) {
  14279. return this;
  14280. }
  14281. if (this.parent.getWorldMatrix().determinant() < 0) {
  14282. this.scalingDeterminant *= -1;
  14283. }
  14284. this._meshToBoneReferal = null;
  14285. this.parent = null;
  14286. return this;
  14287. };
  14288. /**
  14289. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14290. * A mesh is in the frustum if its bounding box intersects the frustum.
  14291. * Boolean returned.
  14292. */
  14293. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14294. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14295. };
  14296. /**
  14297. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14298. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14299. * Boolean returned.
  14300. */
  14301. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14302. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14303. ;
  14304. };
  14305. /**
  14306. * True if the mesh intersects another mesh or a SolidParticle object.
  14307. * 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)
  14308. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14309. * Returns a boolean.
  14310. */
  14311. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14312. if (precise === void 0) { precise = false; }
  14313. if (!this._boundingInfo || !mesh._boundingInfo) {
  14314. return false;
  14315. }
  14316. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14317. return true;
  14318. }
  14319. if (includeDescendants) {
  14320. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14321. var child = _a[_i];
  14322. if (child.intersectsMesh(mesh, precise, true)) {
  14323. return true;
  14324. }
  14325. }
  14326. }
  14327. return false;
  14328. };
  14329. /**
  14330. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14331. * Returns a boolean.
  14332. */
  14333. AbstractMesh.prototype.intersectsPoint = function (point) {
  14334. if (!this._boundingInfo) {
  14335. return false;
  14336. }
  14337. return this._boundingInfo.intersectsPoint(point);
  14338. };
  14339. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14340. return this.physicsImpostor;
  14341. };
  14342. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14343. if (camera === void 0) { camera = null; }
  14344. if (!camera) {
  14345. camera = this.getScene().activeCamera;
  14346. }
  14347. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14348. };
  14349. /**
  14350. * Returns the distance from the mesh to the active camera.
  14351. * Returns a float.
  14352. */
  14353. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14354. if (camera === void 0) { camera = null; }
  14355. if (!camera) {
  14356. camera = this.getScene().activeCamera;
  14357. }
  14358. return this.absolutePosition.subtract(camera.position).length();
  14359. };
  14360. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14361. if (!this.physicsImpostor) {
  14362. return this;
  14363. }
  14364. this.physicsImpostor.applyImpulse(force, contactPoint);
  14365. return this;
  14366. };
  14367. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14368. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14369. return this;
  14370. }
  14371. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14372. mainPivot: pivot1,
  14373. connectedPivot: pivot2,
  14374. nativeParams: options
  14375. });
  14376. return this;
  14377. };
  14378. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14379. // Collisions
  14380. /**
  14381. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14382. * Default `false`.
  14383. */
  14384. get: function () {
  14385. return this._checkCollisions;
  14386. },
  14387. set: function (collisionEnabled) {
  14388. this._checkCollisions = collisionEnabled;
  14389. if (this.getScene().workerCollisions) {
  14390. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14391. }
  14392. },
  14393. enumerable: true,
  14394. configurable: true
  14395. });
  14396. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14397. var globalPosition = this.getAbsolutePosition();
  14398. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14399. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14400. if (!this._collider) {
  14401. this._collider = new BABYLON.Collider();
  14402. }
  14403. this._collider.radius = this.ellipsoid;
  14404. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14405. return this;
  14406. };
  14407. // Submeshes octree
  14408. /**
  14409. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14410. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14411. * Returns an Octree of submeshes.
  14412. */
  14413. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14414. if (maxCapacity === void 0) { maxCapacity = 64; }
  14415. if (maxDepth === void 0) { maxDepth = 2; }
  14416. if (!this._submeshesOctree) {
  14417. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14418. }
  14419. this.computeWorldMatrix(true);
  14420. var boundingInfo = this.getBoundingInfo();
  14421. // Update octree
  14422. if (boundingInfo) {
  14423. var bbox = boundingInfo.boundingBox;
  14424. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14425. }
  14426. return this._submeshesOctree;
  14427. };
  14428. // Collisions
  14429. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14430. this._generatePointsArray();
  14431. if (!this._positions) {
  14432. return this;
  14433. }
  14434. // Transformation
  14435. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14436. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14437. subMesh._lastColliderWorldVertices = [];
  14438. subMesh._trianglePlanes = [];
  14439. var start = subMesh.verticesStart;
  14440. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14441. for (var i = start; i < end; i++) {
  14442. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14443. }
  14444. }
  14445. // Collide
  14446. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14447. if (collider.collisionFound) {
  14448. collider.collidedMesh = this;
  14449. }
  14450. return this;
  14451. };
  14452. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14453. var subMeshes;
  14454. var len;
  14455. // Octrees
  14456. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14457. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14458. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14459. len = intersections.length;
  14460. subMeshes = intersections.data;
  14461. }
  14462. else {
  14463. subMeshes = this.subMeshes;
  14464. len = subMeshes.length;
  14465. }
  14466. for (var index = 0; index < len; index++) {
  14467. var subMesh = subMeshes[index];
  14468. // Bounding test
  14469. if (len > 1 && !subMesh._checkCollision(collider))
  14470. continue;
  14471. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14472. }
  14473. return this;
  14474. };
  14475. AbstractMesh.prototype._checkCollision = function (collider) {
  14476. // Bounding box test
  14477. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14478. return this;
  14479. // Transformation matrix
  14480. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14481. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14482. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14483. return this;
  14484. };
  14485. // Picking
  14486. AbstractMesh.prototype._generatePointsArray = function () {
  14487. return false;
  14488. };
  14489. /**
  14490. * Checks if the passed Ray intersects with the mesh.
  14491. * Returns an object PickingInfo.
  14492. */
  14493. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14494. var pickingInfo = new BABYLON.PickingInfo();
  14495. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14496. return pickingInfo;
  14497. }
  14498. if (!this._generatePointsArray()) {
  14499. return pickingInfo;
  14500. }
  14501. var intersectInfo = null;
  14502. // Octrees
  14503. var subMeshes;
  14504. var len;
  14505. if (this._submeshesOctree && this.useOctreeForPicking) {
  14506. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14507. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14508. len = intersections.length;
  14509. subMeshes = intersections.data;
  14510. }
  14511. else {
  14512. subMeshes = this.subMeshes;
  14513. len = subMeshes.length;
  14514. }
  14515. for (var index = 0; index < len; index++) {
  14516. var subMesh = subMeshes[index];
  14517. // Bounding test
  14518. if (len > 1 && !subMesh.canIntersects(ray))
  14519. continue;
  14520. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14521. if (currentIntersectInfo) {
  14522. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14523. intersectInfo = currentIntersectInfo;
  14524. intersectInfo.subMeshId = index;
  14525. if (fastCheck) {
  14526. break;
  14527. }
  14528. }
  14529. }
  14530. }
  14531. if (intersectInfo) {
  14532. // Get picked point
  14533. var world = this.getWorldMatrix();
  14534. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14535. var direction = ray.direction.clone();
  14536. direction = direction.scale(intersectInfo.distance);
  14537. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14538. var pickedPoint = worldOrigin.add(worldDirection);
  14539. // Return result
  14540. pickingInfo.hit = true;
  14541. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14542. pickingInfo.pickedPoint = pickedPoint;
  14543. pickingInfo.pickedMesh = this;
  14544. pickingInfo.bu = intersectInfo.bu || 0;
  14545. pickingInfo.bv = intersectInfo.bv || 0;
  14546. pickingInfo.faceId = intersectInfo.faceId;
  14547. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14548. return pickingInfo;
  14549. }
  14550. return pickingInfo;
  14551. };
  14552. /**
  14553. * Clones the mesh, used by the class Mesh.
  14554. * Just returns `null` for an AbstractMesh.
  14555. */
  14556. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14557. return null;
  14558. };
  14559. /**
  14560. * Disposes all the mesh submeshes.
  14561. * Returns the AbstractMesh.
  14562. */
  14563. AbstractMesh.prototype.releaseSubMeshes = function () {
  14564. if (this.subMeshes) {
  14565. while (this.subMeshes.length) {
  14566. this.subMeshes[0].dispose();
  14567. }
  14568. }
  14569. else {
  14570. this.subMeshes = new Array();
  14571. }
  14572. return this;
  14573. };
  14574. /**
  14575. * Disposes the AbstractMesh.
  14576. * Some internal references are kept for further use.
  14577. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14578. * Returns nothing.
  14579. */
  14580. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14581. var _this = this;
  14582. var index;
  14583. // Action manager
  14584. if (this.actionManager) {
  14585. this.actionManager.dispose();
  14586. this.actionManager = null;
  14587. }
  14588. // Skeleton
  14589. this.skeleton = null;
  14590. // Animations
  14591. this.getScene().stopAnimation(this);
  14592. // Physics
  14593. if (this.physicsImpostor) {
  14594. this.physicsImpostor.dispose();
  14595. }
  14596. // Intersections in progress
  14597. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14598. var other = this._intersectionsInProgress[index];
  14599. var pos = other._intersectionsInProgress.indexOf(this);
  14600. other._intersectionsInProgress.splice(pos, 1);
  14601. }
  14602. this._intersectionsInProgress = [];
  14603. // Lights
  14604. var lights = this.getScene().lights;
  14605. lights.forEach(function (light) {
  14606. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14607. if (meshIndex !== -1) {
  14608. light.includedOnlyMeshes.splice(meshIndex, 1);
  14609. }
  14610. meshIndex = light.excludedMeshes.indexOf(_this);
  14611. if (meshIndex !== -1) {
  14612. light.excludedMeshes.splice(meshIndex, 1);
  14613. }
  14614. // Shadow generators
  14615. var generator = light.getShadowGenerator();
  14616. if (generator) {
  14617. var shadowMap = generator.getShadowMap();
  14618. if (shadowMap && shadowMap.renderList) {
  14619. meshIndex = shadowMap.renderList.indexOf(_this);
  14620. if (meshIndex !== -1) {
  14621. shadowMap.renderList.splice(meshIndex, 1);
  14622. }
  14623. }
  14624. }
  14625. });
  14626. // Edges
  14627. if (this._edgesRenderer) {
  14628. this._edgesRenderer.dispose();
  14629. this._edgesRenderer = null;
  14630. }
  14631. // SubMeshes
  14632. if (this.getClassName() !== "InstancedMesh") {
  14633. this.releaseSubMeshes();
  14634. }
  14635. // Octree
  14636. var sceneOctree = this.getScene().selectionOctree;
  14637. if (sceneOctree) {
  14638. var index = sceneOctree.dynamicContent.indexOf(this);
  14639. if (index !== -1) {
  14640. sceneOctree.dynamicContent.splice(index, 1);
  14641. }
  14642. }
  14643. // Query
  14644. var engine = this.getScene().getEngine();
  14645. if (this._occlusionQuery) {
  14646. this._isOcclusionQueryInProgress = false;
  14647. engine.deleteQuery(this._occlusionQuery);
  14648. this._occlusionQuery = null;
  14649. }
  14650. // Engine
  14651. engine.wipeCaches();
  14652. // Remove from scene
  14653. this.getScene().removeMesh(this);
  14654. if (!doNotRecurse) {
  14655. // Particles
  14656. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14657. if (this.getScene().particleSystems[index].emitter === this) {
  14658. this.getScene().particleSystems[index].dispose();
  14659. index--;
  14660. }
  14661. }
  14662. // Children
  14663. var objects = this.getDescendants(true);
  14664. for (index = 0; index < objects.length; index++) {
  14665. objects[index].dispose();
  14666. }
  14667. }
  14668. else {
  14669. var childMeshes = this.getChildMeshes(true);
  14670. for (index = 0; index < childMeshes.length; index++) {
  14671. var child = childMeshes[index];
  14672. child.parent = null;
  14673. child.computeWorldMatrix(true);
  14674. }
  14675. }
  14676. // facet data
  14677. if (this._facetDataEnabled) {
  14678. this.disableFacetData();
  14679. }
  14680. this.onAfterWorldMatrixUpdateObservable.clear();
  14681. this.onCollideObservable.clear();
  14682. this.onCollisionPositionChangeObservable.clear();
  14683. this._isDisposed = true;
  14684. _super.prototype.dispose.call(this);
  14685. };
  14686. /**
  14687. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14688. * This Vector3 is expressed in the World space.
  14689. */
  14690. AbstractMesh.prototype.getDirection = function (localAxis) {
  14691. var result = BABYLON.Vector3.Zero();
  14692. this.getDirectionToRef(localAxis, result);
  14693. return result;
  14694. };
  14695. /**
  14696. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14697. * localAxis is expressed in the mesh local space.
  14698. * result is computed in the Wordl space from the mesh World matrix.
  14699. * Returns the AbstractMesh.
  14700. */
  14701. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14702. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14703. return this;
  14704. };
  14705. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14706. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14707. if (this.getScene().getRenderId() == 0) {
  14708. this.computeWorldMatrix(true);
  14709. }
  14710. var wm = this.getWorldMatrix();
  14711. if (space == BABYLON.Space.WORLD) {
  14712. var tmat = BABYLON.Tmp.Matrix[0];
  14713. wm.invertToRef(tmat);
  14714. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14715. }
  14716. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14717. this._pivotMatrix.m[12] = -point.x;
  14718. this._pivotMatrix.m[13] = -point.y;
  14719. this._pivotMatrix.m[14] = -point.z;
  14720. this._cache.pivotMatrixUpdated = true;
  14721. return this;
  14722. };
  14723. /**
  14724. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14725. */
  14726. AbstractMesh.prototype.getPivotPoint = function () {
  14727. var point = BABYLON.Vector3.Zero();
  14728. this.getPivotPointToRef(point);
  14729. return point;
  14730. };
  14731. /**
  14732. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14733. * Returns the AbstractMesh.
  14734. */
  14735. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14736. result.x = -this._pivotMatrix.m[12];
  14737. result.y = -this._pivotMatrix.m[13];
  14738. result.z = -this._pivotMatrix.m[14];
  14739. return this;
  14740. };
  14741. /**
  14742. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14743. */
  14744. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14745. var point = BABYLON.Vector3.Zero();
  14746. this.getAbsolutePivotPointToRef(point);
  14747. return point;
  14748. };
  14749. /**
  14750. * Defines the passed mesh as the parent of the current mesh.
  14751. * Returns the AbstractMesh.
  14752. */
  14753. AbstractMesh.prototype.setParent = function (mesh) {
  14754. var parent = mesh;
  14755. if (mesh == null) {
  14756. var rotation = BABYLON.Tmp.Quaternion[0];
  14757. var position = BABYLON.Tmp.Vector3[0];
  14758. var scale = BABYLON.Tmp.Vector3[1];
  14759. this.getWorldMatrix().decompose(scale, rotation, position);
  14760. if (this.rotationQuaternion) {
  14761. this.rotationQuaternion.copyFrom(rotation);
  14762. }
  14763. else {
  14764. rotation.toEulerAnglesToRef(this.rotation);
  14765. }
  14766. this.position.x = position.x;
  14767. this.position.y = position.y;
  14768. this.position.z = position.z;
  14769. }
  14770. else {
  14771. var position = BABYLON.Tmp.Vector3[0];
  14772. var m1 = BABYLON.Tmp.Matrix[0];
  14773. parent.getWorldMatrix().invertToRef(m1);
  14774. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  14775. this.position.copyFrom(position);
  14776. }
  14777. this.parent = parent;
  14778. return this;
  14779. };
  14780. /**
  14781. * Adds the passed mesh as a child to the current mesh.
  14782. * Returns the AbstractMesh.
  14783. */
  14784. AbstractMesh.prototype.addChild = function (mesh) {
  14785. mesh.setParent(this);
  14786. return this;
  14787. };
  14788. /**
  14789. * Removes the passed mesh from the current mesh children list.
  14790. * Returns the AbstractMesh.
  14791. */
  14792. AbstractMesh.prototype.removeChild = function (mesh) {
  14793. mesh.setParent(null);
  14794. return this;
  14795. };
  14796. /**
  14797. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14798. * Returns the AbstractMesh.
  14799. */
  14800. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14801. result.x = this._pivotMatrix.m[12];
  14802. result.y = this._pivotMatrix.m[13];
  14803. result.z = this._pivotMatrix.m[14];
  14804. this.getPivotPointToRef(result);
  14805. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14806. return this;
  14807. };
  14808. // Facet data
  14809. /**
  14810. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14811. * Returns the AbstractMesh.
  14812. */
  14813. AbstractMesh.prototype._initFacetData = function () {
  14814. if (!this._facetNormals) {
  14815. this._facetNormals = new Array();
  14816. }
  14817. if (!this._facetPositions) {
  14818. this._facetPositions = new Array();
  14819. }
  14820. if (!this._facetPartitioning) {
  14821. this._facetPartitioning = new Array();
  14822. }
  14823. this._facetNb = this.getIndices().length / 3;
  14824. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14825. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14826. for (var f = 0; f < this._facetNb; f++) {
  14827. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14828. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14829. }
  14830. this._facetDataEnabled = true;
  14831. return this;
  14832. };
  14833. /**
  14834. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14835. * This method can be called within the render loop.
  14836. * 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.
  14837. * Returns the AbstractMesh.
  14838. */
  14839. AbstractMesh.prototype.updateFacetData = function () {
  14840. if (!this._facetDataEnabled) {
  14841. this._initFacetData();
  14842. }
  14843. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14844. var indices = this.getIndices();
  14845. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14846. var bInfo = this.getBoundingInfo();
  14847. if (!bInfo) {
  14848. return this;
  14849. }
  14850. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14851. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14852. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14853. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14854. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14855. this._subDiv.max = this._partitioningSubdivisions;
  14856. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14857. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14858. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14859. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14860. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14861. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14862. // set the parameters for ComputeNormals()
  14863. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14864. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14865. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14866. this._facetParameters.bInfo = bInfo;
  14867. this._facetParameters.bbSize = this._bbSize;
  14868. this._facetParameters.subDiv = this._subDiv;
  14869. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14870. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14871. return this;
  14872. };
  14873. /**
  14874. * Returns the facetLocalNormals array.
  14875. * The normals are expressed in the mesh local space.
  14876. */
  14877. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14878. if (!this._facetNormals) {
  14879. this.updateFacetData();
  14880. }
  14881. return this._facetNormals;
  14882. };
  14883. /**
  14884. * Returns the facetLocalPositions array.
  14885. * The facet positions are expressed in the mesh local space.
  14886. */
  14887. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14888. if (!this._facetPositions) {
  14889. this.updateFacetData();
  14890. }
  14891. return this._facetPositions;
  14892. };
  14893. /**
  14894. * Returns the facetLocalPartioning array.
  14895. */
  14896. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14897. if (!this._facetPartitioning) {
  14898. this.updateFacetData();
  14899. }
  14900. return this._facetPartitioning;
  14901. };
  14902. /**
  14903. * Returns the i-th facet position in the world system.
  14904. * This method allocates a new Vector3 per call.
  14905. */
  14906. AbstractMesh.prototype.getFacetPosition = function (i) {
  14907. var pos = BABYLON.Vector3.Zero();
  14908. this.getFacetPositionToRef(i, pos);
  14909. return pos;
  14910. };
  14911. /**
  14912. * Sets the reference Vector3 with the i-th facet position in the world system.
  14913. * Returns the AbstractMesh.
  14914. */
  14915. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14916. var localPos = (this.getFacetLocalPositions())[i];
  14917. var world = this.getWorldMatrix();
  14918. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14919. return this;
  14920. };
  14921. /**
  14922. * Returns the i-th facet normal in the world system.
  14923. * This method allocates a new Vector3 per call.
  14924. */
  14925. AbstractMesh.prototype.getFacetNormal = function (i) {
  14926. var norm = BABYLON.Vector3.Zero();
  14927. this.getFacetNormalToRef(i, norm);
  14928. return norm;
  14929. };
  14930. /**
  14931. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14932. * Returns the AbstractMesh.
  14933. */
  14934. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14935. var localNorm = (this.getFacetLocalNormals())[i];
  14936. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14937. return this;
  14938. };
  14939. /**
  14940. * 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).
  14941. */
  14942. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14943. var bInfo = this.getBoundingInfo();
  14944. if (!bInfo) {
  14945. return null;
  14946. }
  14947. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14948. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14949. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14950. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14951. return null;
  14952. }
  14953. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14954. };
  14955. /**
  14956. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14957. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14958. * 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.
  14959. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14960. * 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.
  14961. */
  14962. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14963. if (checkFace === void 0) { checkFace = false; }
  14964. if (facing === void 0) { facing = true; }
  14965. var world = this.getWorldMatrix();
  14966. var invMat = BABYLON.Tmp.Matrix[5];
  14967. world.invertToRef(invMat);
  14968. var invVect = BABYLON.Tmp.Vector3[8];
  14969. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14970. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14971. if (projected) {
  14972. // tranform the local computed projected vector to world coordinates
  14973. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14974. }
  14975. return closest;
  14976. };
  14977. /**
  14978. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14979. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14980. * 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.
  14981. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14982. * 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.
  14983. */
  14984. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14985. if (checkFace === void 0) { checkFace = false; }
  14986. if (facing === void 0) { facing = true; }
  14987. var closest = null;
  14988. var tmpx = 0.0;
  14989. var tmpy = 0.0;
  14990. var tmpz = 0.0;
  14991. var d = 0.0; // tmp dot facet normal * facet position
  14992. var t0 = 0.0;
  14993. var projx = 0.0;
  14994. var projy = 0.0;
  14995. var projz = 0.0;
  14996. // Get all the facets in the same partitioning block than (x, y, z)
  14997. var facetPositions = this.getFacetLocalPositions();
  14998. var facetNormals = this.getFacetLocalNormals();
  14999. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15000. if (!facetsInBlock) {
  15001. return null;
  15002. }
  15003. // Get the closest facet to (x, y, z)
  15004. var shortest = Number.MAX_VALUE; // init distance vars
  15005. var tmpDistance = shortest;
  15006. var fib; // current facet in the block
  15007. var norm; // current facet normal
  15008. var p0; // current facet barycenter position
  15009. // loop on all the facets in the current partitioning block
  15010. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15011. fib = facetsInBlock[idx];
  15012. norm = facetNormals[fib];
  15013. p0 = facetPositions[fib];
  15014. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15015. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15016. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15017. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15018. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15019. projx = x + norm.x * t0;
  15020. projy = y + norm.y * t0;
  15021. projz = z + norm.z * t0;
  15022. tmpx = projx - x;
  15023. tmpy = projy - y;
  15024. tmpz = projz - z;
  15025. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15026. if (tmpDistance < shortest) {
  15027. shortest = tmpDistance;
  15028. closest = fib;
  15029. if (projected) {
  15030. projected.x = projx;
  15031. projected.y = projy;
  15032. projected.z = projz;
  15033. }
  15034. }
  15035. }
  15036. }
  15037. return closest;
  15038. };
  15039. /**
  15040. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15041. */
  15042. AbstractMesh.prototype.getFacetDataParameters = function () {
  15043. return this._facetParameters;
  15044. };
  15045. /**
  15046. * Disables the feature FacetData and frees the related memory.
  15047. * Returns the AbstractMesh.
  15048. */
  15049. AbstractMesh.prototype.disableFacetData = function () {
  15050. if (this._facetDataEnabled) {
  15051. this._facetDataEnabled = false;
  15052. this._facetPositions = new Array();
  15053. ;
  15054. this._facetNormals = new Array();
  15055. ;
  15056. this._facetPartitioning = new Array();
  15057. ;
  15058. this._facetParameters = null;
  15059. }
  15060. return this;
  15061. };
  15062. /**
  15063. * Creates new normals data for the mesh.
  15064. * @param updatable.
  15065. */
  15066. AbstractMesh.prototype.createNormals = function (updatable) {
  15067. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15068. var indices = this.getIndices();
  15069. var normals;
  15070. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15071. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15072. }
  15073. else {
  15074. normals = [];
  15075. }
  15076. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15077. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15078. };
  15079. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15080. var engine = this.getEngine();
  15081. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15082. this._isOccluded = false;
  15083. return;
  15084. }
  15085. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15086. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15087. if (isOcclusionQueryAvailable) {
  15088. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15089. this._isOcclusionQueryInProgress = false;
  15090. this._occlusionInternalRetryCounter = 0;
  15091. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15092. }
  15093. else {
  15094. this._occlusionInternalRetryCounter++;
  15095. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15096. this._isOcclusionQueryInProgress = false;
  15097. this._occlusionInternalRetryCounter = 0;
  15098. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15099. // if strict continue the last state of the object.
  15100. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15101. }
  15102. else {
  15103. return;
  15104. }
  15105. }
  15106. }
  15107. var scene = this.getScene();
  15108. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15109. if (!this._occlusionQuery) {
  15110. this._occlusionQuery = engine.createQuery();
  15111. }
  15112. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15113. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15114. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15115. this._isOcclusionQueryInProgress = true;
  15116. };
  15117. // Statics
  15118. AbstractMesh._BILLBOARDMODE_NONE = 0;
  15119. AbstractMesh._BILLBOARDMODE_X = 1;
  15120. AbstractMesh._BILLBOARDMODE_Y = 2;
  15121. AbstractMesh._BILLBOARDMODE_Z = 4;
  15122. AbstractMesh._BILLBOARDMODE_ALL = 7;
  15123. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15124. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15125. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15126. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15127. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15128. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  15129. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15130. return AbstractMesh;
  15131. }(BABYLON.Node));
  15132. BABYLON.AbstractMesh = AbstractMesh;
  15133. })(BABYLON || (BABYLON = {}));
  15134. //# sourceMappingURL=babylon.abstractMesh.js.map
  15135. var BABYLON;
  15136. (function (BABYLON) {
  15137. var Light = /** @class */ (function (_super) {
  15138. __extends(Light, _super);
  15139. /**
  15140. * Creates a Light object in the scene.
  15141. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15142. */
  15143. function Light(name, scene) {
  15144. var _this = _super.call(this, name, scene) || this;
  15145. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15146. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15147. _this.intensity = 1.0;
  15148. _this.range = Number.MAX_VALUE;
  15149. /**
  15150. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15151. * of light.
  15152. */
  15153. _this._photometricScale = 1.0;
  15154. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15155. _this._radius = 0.00001;
  15156. _this.renderPriority = 0;
  15157. /**
  15158. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15159. * the current shadow generator.
  15160. */
  15161. _this.shadowEnabled = true;
  15162. _this._excludeWithLayerMask = 0;
  15163. _this._includeOnlyWithLayerMask = 0;
  15164. _this._lightmapMode = 0;
  15165. _this._excludedMeshesIds = new Array();
  15166. _this._includedOnlyMeshesIds = new Array();
  15167. _this.getScene().addLight(_this);
  15168. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15169. _this._buildUniformLayout();
  15170. _this.includedOnlyMeshes = new Array();
  15171. _this.excludedMeshes = new Array();
  15172. _this._resyncMeshes();
  15173. return _this;
  15174. }
  15175. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15176. /**
  15177. * If every light affecting the material is in this lightmapMode,
  15178. * material.lightmapTexture adds or multiplies
  15179. * (depends on material.useLightmapAsShadowmap)
  15180. * after every other light calculations.
  15181. */
  15182. get: function () {
  15183. return Light._LIGHTMAP_DEFAULT;
  15184. },
  15185. enumerable: true,
  15186. configurable: true
  15187. });
  15188. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15189. /**
  15190. * material.lightmapTexture as only diffuse lighting from this light
  15191. * adds pnly specular lighting from this light
  15192. * adds dynamic shadows
  15193. */
  15194. get: function () {
  15195. return Light._LIGHTMAP_SPECULAR;
  15196. },
  15197. enumerable: true,
  15198. configurable: true
  15199. });
  15200. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15201. /**
  15202. * material.lightmapTexture as only lighting
  15203. * no light calculation from this light
  15204. * only adds dynamic shadows from this light
  15205. */
  15206. get: function () {
  15207. return Light._LIGHTMAP_SHADOWSONLY;
  15208. },
  15209. enumerable: true,
  15210. configurable: true
  15211. });
  15212. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15213. /**
  15214. * Each light type uses the default quantity according to its type:
  15215. * point/spot lights use luminous intensity
  15216. * directional lights use illuminance
  15217. */
  15218. get: function () {
  15219. return Light._INTENSITYMODE_AUTOMATIC;
  15220. },
  15221. enumerable: true,
  15222. configurable: true
  15223. });
  15224. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15225. /**
  15226. * lumen (lm)
  15227. */
  15228. get: function () {
  15229. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15230. },
  15231. enumerable: true,
  15232. configurable: true
  15233. });
  15234. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15235. /**
  15236. * candela (lm/sr)
  15237. */
  15238. get: function () {
  15239. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15240. },
  15241. enumerable: true,
  15242. configurable: true
  15243. });
  15244. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15245. /**
  15246. * lux (lm/m^2)
  15247. */
  15248. get: function () {
  15249. return Light._INTENSITYMODE_ILLUMINANCE;
  15250. },
  15251. enumerable: true,
  15252. configurable: true
  15253. });
  15254. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15255. /**
  15256. * nit (cd/m^2)
  15257. */
  15258. get: function () {
  15259. return Light._INTENSITYMODE_LUMINANCE;
  15260. },
  15261. enumerable: true,
  15262. configurable: true
  15263. });
  15264. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15265. /**
  15266. * Light type const id of the point light.
  15267. */
  15268. get: function () {
  15269. return Light._LIGHTTYPEID_POINTLIGHT;
  15270. },
  15271. enumerable: true,
  15272. configurable: true
  15273. });
  15274. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15275. /**
  15276. * Light type const id of the directional light.
  15277. */
  15278. get: function () {
  15279. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15280. },
  15281. enumerable: true,
  15282. configurable: true
  15283. });
  15284. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15285. /**
  15286. * Light type const id of the spot light.
  15287. */
  15288. get: function () {
  15289. return Light._LIGHTTYPEID_SPOTLIGHT;
  15290. },
  15291. enumerable: true,
  15292. configurable: true
  15293. });
  15294. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15295. /**
  15296. * Light type const id of the hemispheric light.
  15297. */
  15298. get: function () {
  15299. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15300. },
  15301. enumerable: true,
  15302. configurable: true
  15303. });
  15304. Object.defineProperty(Light.prototype, "intensityMode", {
  15305. /**
  15306. * Gets the photometric scale used to interpret the intensity.
  15307. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15308. */
  15309. get: function () {
  15310. return this._intensityMode;
  15311. },
  15312. /**
  15313. * Sets the photometric scale used to interpret the intensity.
  15314. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15315. */
  15316. set: function (value) {
  15317. this._intensityMode = value;
  15318. this._computePhotometricScale();
  15319. },
  15320. enumerable: true,
  15321. configurable: true
  15322. });
  15323. ;
  15324. ;
  15325. Object.defineProperty(Light.prototype, "radius", {
  15326. /**
  15327. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15328. */
  15329. get: function () {
  15330. return this._radius;
  15331. },
  15332. /**
  15333. * sets the light radius used by PBR Materials to simulate soft area lights.
  15334. */
  15335. set: function (value) {
  15336. this._radius = value;
  15337. this._computePhotometricScale();
  15338. },
  15339. enumerable: true,
  15340. configurable: true
  15341. });
  15342. ;
  15343. ;
  15344. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15345. get: function () {
  15346. return this._includedOnlyMeshes;
  15347. },
  15348. set: function (value) {
  15349. this._includedOnlyMeshes = value;
  15350. this._hookArrayForIncludedOnly(value);
  15351. },
  15352. enumerable: true,
  15353. configurable: true
  15354. });
  15355. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15356. get: function () {
  15357. return this._excludedMeshes;
  15358. },
  15359. set: function (value) {
  15360. this._excludedMeshes = value;
  15361. this._hookArrayForExcluded(value);
  15362. },
  15363. enumerable: true,
  15364. configurable: true
  15365. });
  15366. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15367. get: function () {
  15368. return this._excludeWithLayerMask;
  15369. },
  15370. set: function (value) {
  15371. this._excludeWithLayerMask = value;
  15372. this._resyncMeshes();
  15373. },
  15374. enumerable: true,
  15375. configurable: true
  15376. });
  15377. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15378. get: function () {
  15379. return this._includeOnlyWithLayerMask;
  15380. },
  15381. set: function (value) {
  15382. this._includeOnlyWithLayerMask = value;
  15383. this._resyncMeshes();
  15384. },
  15385. enumerable: true,
  15386. configurable: true
  15387. });
  15388. Object.defineProperty(Light.prototype, "lightmapMode", {
  15389. get: function () {
  15390. return this._lightmapMode;
  15391. },
  15392. set: function (value) {
  15393. if (this._lightmapMode === value) {
  15394. return;
  15395. }
  15396. this._lightmapMode = value;
  15397. this._markMeshesAsLightDirty();
  15398. },
  15399. enumerable: true,
  15400. configurable: true
  15401. });
  15402. Light.prototype._buildUniformLayout = function () {
  15403. // Overridden
  15404. };
  15405. /**
  15406. * Returns the string "Light".
  15407. */
  15408. Light.prototype.getClassName = function () {
  15409. return "Light";
  15410. };
  15411. /**
  15412. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15413. */
  15414. Light.prototype.toString = function (fullDetails) {
  15415. var ret = "Name: " + this.name;
  15416. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15417. if (this.animations) {
  15418. for (var i = 0; i < this.animations.length; i++) {
  15419. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15420. }
  15421. }
  15422. if (fullDetails) {
  15423. }
  15424. return ret;
  15425. };
  15426. /**
  15427. * Set the enabled state of this node.
  15428. * @param {boolean} value - the new enabled state
  15429. * @see isEnabled
  15430. */
  15431. Light.prototype.setEnabled = function (value) {
  15432. _super.prototype.setEnabled.call(this, value);
  15433. this._resyncMeshes();
  15434. };
  15435. /**
  15436. * Returns the Light associated shadow generator.
  15437. */
  15438. Light.prototype.getShadowGenerator = function () {
  15439. return this._shadowGenerator;
  15440. };
  15441. /**
  15442. * Returns a Vector3, the absolute light position in the World.
  15443. */
  15444. Light.prototype.getAbsolutePosition = function () {
  15445. return BABYLON.Vector3.Zero();
  15446. };
  15447. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15448. };
  15449. Light.prototype._getWorldMatrix = function () {
  15450. return BABYLON.Matrix.Identity();
  15451. };
  15452. /**
  15453. * Boolean : True if the light will affect the passed mesh.
  15454. */
  15455. Light.prototype.canAffectMesh = function (mesh) {
  15456. if (!mesh) {
  15457. return true;
  15458. }
  15459. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15460. return false;
  15461. }
  15462. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15463. return false;
  15464. }
  15465. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15466. return false;
  15467. }
  15468. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15469. return false;
  15470. }
  15471. return true;
  15472. };
  15473. /**
  15474. * Returns the light World matrix.
  15475. */
  15476. Light.prototype.getWorldMatrix = function () {
  15477. this._currentRenderId = this.getScene().getRenderId();
  15478. var worldMatrix = this._getWorldMatrix();
  15479. if (this.parent && this.parent.getWorldMatrix) {
  15480. if (!this._parentedWorldMatrix) {
  15481. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15482. }
  15483. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15484. this._markSyncedWithParent();
  15485. return this._parentedWorldMatrix;
  15486. }
  15487. return worldMatrix;
  15488. };
  15489. /**
  15490. * Sort function to order lights for rendering.
  15491. * @param a First Light object to compare to second.
  15492. * @param b Second Light object to compare first.
  15493. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15494. */
  15495. Light.compareLightsPriority = function (a, b) {
  15496. //shadow-casting lights have priority over non-shadow-casting lights
  15497. //the renderPrioirty is a secondary sort criterion
  15498. if (a.shadowEnabled !== b.shadowEnabled) {
  15499. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15500. }
  15501. return b.renderPriority - a.renderPriority;
  15502. };
  15503. /**
  15504. * Disposes the light.
  15505. */
  15506. Light.prototype.dispose = function () {
  15507. if (this._shadowGenerator) {
  15508. this._shadowGenerator.dispose();
  15509. this._shadowGenerator = null;
  15510. }
  15511. // Animations
  15512. this.getScene().stopAnimation(this);
  15513. // Remove from meshes
  15514. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15515. var mesh = _a[_i];
  15516. mesh._removeLightSource(this);
  15517. }
  15518. this._uniformBuffer.dispose();
  15519. // Remove from scene
  15520. this.getScene().removeLight(this);
  15521. _super.prototype.dispose.call(this);
  15522. };
  15523. /**
  15524. * Returns the light type ID (integer).
  15525. */
  15526. Light.prototype.getTypeID = function () {
  15527. return 0;
  15528. };
  15529. /**
  15530. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15531. */
  15532. Light.prototype.getScaledIntensity = function () {
  15533. return this._photometricScale * this.intensity;
  15534. };
  15535. /**
  15536. * Returns a new Light object, named "name", from the current one.
  15537. */
  15538. Light.prototype.clone = function (name) {
  15539. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15540. if (!constructor) {
  15541. return null;
  15542. }
  15543. return BABYLON.SerializationHelper.Clone(constructor, this);
  15544. };
  15545. /**
  15546. * Serializes the current light into a Serialization object.
  15547. * Returns the serialized object.
  15548. */
  15549. Light.prototype.serialize = function () {
  15550. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15551. // Type
  15552. serializationObject.type = this.getTypeID();
  15553. // Parent
  15554. if (this.parent) {
  15555. serializationObject.parentId = this.parent.id;
  15556. }
  15557. // Inclusion / exclusions
  15558. if (this.excludedMeshes.length > 0) {
  15559. serializationObject.excludedMeshesIds = [];
  15560. this.excludedMeshes.forEach(function (mesh) {
  15561. serializationObject.excludedMeshesIds.push(mesh.id);
  15562. });
  15563. }
  15564. if (this.includedOnlyMeshes.length > 0) {
  15565. serializationObject.includedOnlyMeshesIds = [];
  15566. this.includedOnlyMeshes.forEach(function (mesh) {
  15567. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15568. });
  15569. }
  15570. // Animations
  15571. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15572. serializationObject.ranges = this.serializeAnimationRanges();
  15573. return serializationObject;
  15574. };
  15575. /**
  15576. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15577. * This new light is named "name" and added to the passed scene.
  15578. */
  15579. Light.GetConstructorFromName = function (type, name, scene) {
  15580. switch (type) {
  15581. case 0:
  15582. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15583. case 1:
  15584. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15585. case 2:
  15586. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15587. case 3:
  15588. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15589. }
  15590. return null;
  15591. };
  15592. /**
  15593. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15594. */
  15595. Light.Parse = function (parsedLight, scene) {
  15596. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15597. if (!constructor) {
  15598. return null;
  15599. }
  15600. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15601. // Inclusion / exclusions
  15602. if (parsedLight.excludedMeshesIds) {
  15603. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15604. }
  15605. if (parsedLight.includedOnlyMeshesIds) {
  15606. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15607. }
  15608. // Parent
  15609. if (parsedLight.parentId) {
  15610. light._waitingParentId = parsedLight.parentId;
  15611. }
  15612. // Animations
  15613. if (parsedLight.animations) {
  15614. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15615. var parsedAnimation = parsedLight.animations[animationIndex];
  15616. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15617. }
  15618. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15619. }
  15620. if (parsedLight.autoAnimate) {
  15621. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15622. }
  15623. return light;
  15624. };
  15625. Light.prototype._hookArrayForExcluded = function (array) {
  15626. var _this = this;
  15627. var oldPush = array.push;
  15628. array.push = function () {
  15629. var items = [];
  15630. for (var _i = 0; _i < arguments.length; _i++) {
  15631. items[_i] = arguments[_i];
  15632. }
  15633. var result = oldPush.apply(array, items);
  15634. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15635. var item = items_1[_a];
  15636. item._resyncLighSource(_this);
  15637. }
  15638. return result;
  15639. };
  15640. var oldSplice = array.splice;
  15641. array.splice = function (index, deleteCount) {
  15642. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15643. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15644. var item = deleted_1[_i];
  15645. item._resyncLighSource(_this);
  15646. }
  15647. return deleted;
  15648. };
  15649. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15650. var item = array_1[_i];
  15651. item._resyncLighSource(this);
  15652. }
  15653. };
  15654. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15655. var _this = this;
  15656. var oldPush = array.push;
  15657. array.push = function () {
  15658. var items = [];
  15659. for (var _i = 0; _i < arguments.length; _i++) {
  15660. items[_i] = arguments[_i];
  15661. }
  15662. var result = oldPush.apply(array, items);
  15663. _this._resyncMeshes();
  15664. return result;
  15665. };
  15666. var oldSplice = array.splice;
  15667. array.splice = function (index, deleteCount) {
  15668. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15669. _this._resyncMeshes();
  15670. return deleted;
  15671. };
  15672. this._resyncMeshes();
  15673. };
  15674. Light.prototype._resyncMeshes = function () {
  15675. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15676. var mesh = _a[_i];
  15677. mesh._resyncLighSource(this);
  15678. }
  15679. };
  15680. Light.prototype._markMeshesAsLightDirty = function () {
  15681. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15682. var mesh = _a[_i];
  15683. if (mesh._lightSources.indexOf(this) !== -1) {
  15684. mesh._markSubMeshesAsLightDirty();
  15685. }
  15686. }
  15687. };
  15688. /**
  15689. * Recomputes the cached photometric scale if needed.
  15690. */
  15691. Light.prototype._computePhotometricScale = function () {
  15692. this._photometricScale = this._getPhotometricScale();
  15693. this.getScene().resetCachedMaterial();
  15694. };
  15695. /**
  15696. * Returns the Photometric Scale according to the light type and intensity mode.
  15697. */
  15698. Light.prototype._getPhotometricScale = function () {
  15699. var photometricScale = 0.0;
  15700. var lightTypeID = this.getTypeID();
  15701. //get photometric mode
  15702. var photometricMode = this.intensityMode;
  15703. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15704. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15705. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15706. }
  15707. else {
  15708. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15709. }
  15710. }
  15711. //compute photometric scale
  15712. switch (lightTypeID) {
  15713. case Light.LIGHTTYPEID_POINTLIGHT:
  15714. case Light.LIGHTTYPEID_SPOTLIGHT:
  15715. switch (photometricMode) {
  15716. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15717. photometricScale = 1.0 / (4.0 * Math.PI);
  15718. break;
  15719. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15720. photometricScale = 1.0;
  15721. break;
  15722. case Light.INTENSITYMODE_LUMINANCE:
  15723. photometricScale = this.radius * this.radius;
  15724. break;
  15725. }
  15726. break;
  15727. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15728. switch (photometricMode) {
  15729. case Light.INTENSITYMODE_ILLUMINANCE:
  15730. photometricScale = 1.0;
  15731. break;
  15732. case Light.INTENSITYMODE_LUMINANCE:
  15733. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15734. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15735. var apexAngleRadians = this.radius;
  15736. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15737. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15738. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15739. photometricScale = solidAngle;
  15740. break;
  15741. }
  15742. break;
  15743. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15744. // No fall off in hemisperic light.
  15745. photometricScale = 1.0;
  15746. break;
  15747. }
  15748. return photometricScale;
  15749. };
  15750. Light.prototype._reorderLightsInScene = function () {
  15751. var scene = this.getScene();
  15752. if (this._renderPriority != 0) {
  15753. scene.requireLightSorting = true;
  15754. }
  15755. this.getScene().sortLightsByPriority();
  15756. };
  15757. //lightmapMode Consts
  15758. Light._LIGHTMAP_DEFAULT = 0;
  15759. Light._LIGHTMAP_SPECULAR = 1;
  15760. Light._LIGHTMAP_SHADOWSONLY = 2;
  15761. // Intensity Mode Consts
  15762. Light._INTENSITYMODE_AUTOMATIC = 0;
  15763. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15764. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15765. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15766. Light._INTENSITYMODE_LUMINANCE = 4;
  15767. // Light types ids const.
  15768. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15769. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15770. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15771. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15772. __decorate([
  15773. BABYLON.serializeAsColor3()
  15774. ], Light.prototype, "diffuse", void 0);
  15775. __decorate([
  15776. BABYLON.serializeAsColor3()
  15777. ], Light.prototype, "specular", void 0);
  15778. __decorate([
  15779. BABYLON.serialize()
  15780. ], Light.prototype, "intensity", void 0);
  15781. __decorate([
  15782. BABYLON.serialize()
  15783. ], Light.prototype, "range", void 0);
  15784. __decorate([
  15785. BABYLON.serialize()
  15786. ], Light.prototype, "intensityMode", null);
  15787. __decorate([
  15788. BABYLON.serialize()
  15789. ], Light.prototype, "radius", null);
  15790. __decorate([
  15791. BABYLON.serialize()
  15792. ], Light.prototype, "_renderPriority", void 0);
  15793. __decorate([
  15794. BABYLON.expandToProperty("_reorderLightsInScene")
  15795. ], Light.prototype, "renderPriority", void 0);
  15796. __decorate([
  15797. BABYLON.serialize()
  15798. ], Light.prototype, "shadowEnabled", void 0);
  15799. __decorate([
  15800. BABYLON.serialize("excludeWithLayerMask")
  15801. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15802. __decorate([
  15803. BABYLON.serialize("includeOnlyWithLayerMask")
  15804. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15805. __decorate([
  15806. BABYLON.serialize("lightmapMode")
  15807. ], Light.prototype, "_lightmapMode", void 0);
  15808. return Light;
  15809. }(BABYLON.Node));
  15810. BABYLON.Light = Light;
  15811. })(BABYLON || (BABYLON = {}));
  15812. //# sourceMappingURL=babylon.light.js.map
  15813. var BABYLON;
  15814. (function (BABYLON) {
  15815. var Camera = /** @class */ (function (_super) {
  15816. __extends(Camera, _super);
  15817. function Camera(name, position, scene) {
  15818. var _this = _super.call(this, name, scene) || this;
  15819. _this.upVector = BABYLON.Vector3.Up();
  15820. _this.orthoLeft = null;
  15821. _this.orthoRight = null;
  15822. _this.orthoBottom = null;
  15823. _this.orthoTop = null;
  15824. _this.fov = 0.8;
  15825. _this.minZ = 1;
  15826. _this.maxZ = 10000.0;
  15827. _this.inertia = 0.9;
  15828. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15829. _this.isIntermediate = false;
  15830. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15831. _this.layerMask = 0x0FFFFFFF;
  15832. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15833. // Camera rig members
  15834. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15835. _this._rigCameras = new Array();
  15836. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15837. _this._skipRendering = false;
  15838. _this.customRenderTargets = new Array();
  15839. // Observables
  15840. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15841. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15842. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15843. _this.onRestoreStateObservable = new BABYLON.Observable();
  15844. // Cache
  15845. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15846. _this._projectionMatrix = new BABYLON.Matrix();
  15847. _this._doNotComputeProjectionMatrix = false;
  15848. _this._postProcesses = new Array();
  15849. _this._transformMatrix = BABYLON.Matrix.Zero();
  15850. _this._activeMeshes = new BABYLON.SmartArray(256);
  15851. _this._globalPosition = BABYLON.Vector3.Zero();
  15852. _this._refreshFrustumPlanes = true;
  15853. _this.getScene().addCamera(_this);
  15854. if (!_this.getScene().activeCamera) {
  15855. _this.getScene().activeCamera = _this;
  15856. }
  15857. _this.position = position;
  15858. return _this;
  15859. }
  15860. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15861. get: function () {
  15862. return Camera._PERSPECTIVE_CAMERA;
  15863. },
  15864. enumerable: true,
  15865. configurable: true
  15866. });
  15867. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15868. get: function () {
  15869. return Camera._ORTHOGRAPHIC_CAMERA;
  15870. },
  15871. enumerable: true,
  15872. configurable: true
  15873. });
  15874. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15875. get: function () {
  15876. return Camera._FOVMODE_VERTICAL_FIXED;
  15877. },
  15878. enumerable: true,
  15879. configurable: true
  15880. });
  15881. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15882. get: function () {
  15883. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15884. },
  15885. enumerable: true,
  15886. configurable: true
  15887. });
  15888. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15889. get: function () {
  15890. return Camera._RIG_MODE_NONE;
  15891. },
  15892. enumerable: true,
  15893. configurable: true
  15894. });
  15895. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15896. get: function () {
  15897. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15898. },
  15899. enumerable: true,
  15900. configurable: true
  15901. });
  15902. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15903. get: function () {
  15904. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15905. },
  15906. enumerable: true,
  15907. configurable: true
  15908. });
  15909. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15910. get: function () {
  15911. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15912. },
  15913. enumerable: true,
  15914. configurable: true
  15915. });
  15916. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15917. get: function () {
  15918. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15919. },
  15920. enumerable: true,
  15921. configurable: true
  15922. });
  15923. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15924. get: function () {
  15925. return Camera._RIG_MODE_VR;
  15926. },
  15927. enumerable: true,
  15928. configurable: true
  15929. });
  15930. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15931. get: function () {
  15932. return Camera._RIG_MODE_WEBVR;
  15933. },
  15934. enumerable: true,
  15935. configurable: true
  15936. });
  15937. /**
  15938. * Store current camera state (fov, position, etc..)
  15939. */
  15940. Camera.prototype.storeState = function () {
  15941. this._stateStored = true;
  15942. this._storedFov = this.fov;
  15943. return this;
  15944. };
  15945. /**
  15946. * Restores the camera state values if it has been stored. You must call storeState() first
  15947. */
  15948. Camera.prototype._restoreStateValues = function () {
  15949. if (!this._stateStored) {
  15950. return false;
  15951. }
  15952. this.fov = this._storedFov;
  15953. return true;
  15954. };
  15955. /**
  15956. * Restored camera state. You must call storeState() first
  15957. */
  15958. Camera.prototype.restoreState = function () {
  15959. if (this._restoreStateValues()) {
  15960. this.onRestoreStateObservable.notifyObservers(this);
  15961. return true;
  15962. }
  15963. return false;
  15964. };
  15965. Camera.prototype.getClassName = function () {
  15966. return "Camera";
  15967. };
  15968. /**
  15969. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15970. */
  15971. Camera.prototype.toString = function (fullDetails) {
  15972. var ret = "Name: " + this.name;
  15973. ret += ", type: " + this.getClassName();
  15974. if (this.animations) {
  15975. for (var i = 0; i < this.animations.length; i++) {
  15976. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15977. }
  15978. }
  15979. if (fullDetails) {
  15980. }
  15981. return ret;
  15982. };
  15983. Object.defineProperty(Camera.prototype, "globalPosition", {
  15984. get: function () {
  15985. return this._globalPosition;
  15986. },
  15987. enumerable: true,
  15988. configurable: true
  15989. });
  15990. Camera.prototype.getActiveMeshes = function () {
  15991. return this._activeMeshes;
  15992. };
  15993. Camera.prototype.isActiveMesh = function (mesh) {
  15994. return (this._activeMeshes.indexOf(mesh) !== -1);
  15995. };
  15996. //Cache
  15997. Camera.prototype._initCache = function () {
  15998. _super.prototype._initCache.call(this);
  15999. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16000. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16001. this._cache.mode = undefined;
  16002. this._cache.minZ = undefined;
  16003. this._cache.maxZ = undefined;
  16004. this._cache.fov = undefined;
  16005. this._cache.fovMode = undefined;
  16006. this._cache.aspectRatio = undefined;
  16007. this._cache.orthoLeft = undefined;
  16008. this._cache.orthoRight = undefined;
  16009. this._cache.orthoBottom = undefined;
  16010. this._cache.orthoTop = undefined;
  16011. this._cache.renderWidth = undefined;
  16012. this._cache.renderHeight = undefined;
  16013. };
  16014. Camera.prototype._updateCache = function (ignoreParentClass) {
  16015. if (!ignoreParentClass) {
  16016. _super.prototype._updateCache.call(this);
  16017. }
  16018. this._cache.position.copyFrom(this.position);
  16019. this._cache.upVector.copyFrom(this.upVector);
  16020. };
  16021. // Synchronized
  16022. Camera.prototype._isSynchronized = function () {
  16023. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16024. };
  16025. Camera.prototype._isSynchronizedViewMatrix = function () {
  16026. if (!_super.prototype._isSynchronized.call(this))
  16027. return false;
  16028. return this._cache.position.equals(this.position)
  16029. && this._cache.upVector.equals(this.upVector)
  16030. && this.isSynchronizedWithParent();
  16031. };
  16032. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16033. var check = this._cache.mode === this.mode
  16034. && this._cache.minZ === this.minZ
  16035. && this._cache.maxZ === this.maxZ;
  16036. if (!check) {
  16037. return false;
  16038. }
  16039. var engine = this.getEngine();
  16040. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16041. check = this._cache.fov === this.fov
  16042. && this._cache.fovMode === this.fovMode
  16043. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16044. }
  16045. else {
  16046. check = this._cache.orthoLeft === this.orthoLeft
  16047. && this._cache.orthoRight === this.orthoRight
  16048. && this._cache.orthoBottom === this.orthoBottom
  16049. && this._cache.orthoTop === this.orthoTop
  16050. && this._cache.renderWidth === engine.getRenderWidth()
  16051. && this._cache.renderHeight === engine.getRenderHeight();
  16052. }
  16053. return check;
  16054. };
  16055. // Controls
  16056. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16057. };
  16058. Camera.prototype.detachControl = function (element) {
  16059. };
  16060. Camera.prototype.update = function () {
  16061. this._checkInputs();
  16062. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16063. this._updateRigCameras();
  16064. }
  16065. };
  16066. Camera.prototype._checkInputs = function () {
  16067. this.onAfterCheckInputsObservable.notifyObservers(this);
  16068. };
  16069. Object.defineProperty(Camera.prototype, "rigCameras", {
  16070. get: function () {
  16071. return this._rigCameras;
  16072. },
  16073. enumerable: true,
  16074. configurable: true
  16075. });
  16076. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16077. get: function () {
  16078. return this._rigPostProcess;
  16079. },
  16080. enumerable: true,
  16081. configurable: true
  16082. });
  16083. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16084. // invalidate framebuffer
  16085. if (this._postProcesses.length > 0) {
  16086. this._postProcesses[0].markTextureDirty();
  16087. }
  16088. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16089. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16090. var cam = this._rigCameras[i];
  16091. var rigPostProcess = cam._rigPostProcess;
  16092. // for VR rig, there does not have to be a post process
  16093. if (rigPostProcess) {
  16094. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16095. if (isPass) {
  16096. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16097. cam.isIntermediate = this._postProcesses.length === 0;
  16098. }
  16099. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16100. rigPostProcess.markTextureDirty();
  16101. }
  16102. else {
  16103. cam._postProcesses = this._postProcesses.slice(0);
  16104. }
  16105. }
  16106. };
  16107. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16108. if (insertAt === void 0) { insertAt = null; }
  16109. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16110. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16111. return 0;
  16112. }
  16113. if (insertAt == null || insertAt < 0) {
  16114. this._postProcesses.push(postProcess);
  16115. }
  16116. else {
  16117. this._postProcesses.splice(insertAt, 0, postProcess);
  16118. }
  16119. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16120. return this._postProcesses.indexOf(postProcess);
  16121. };
  16122. Camera.prototype.detachPostProcess = function (postProcess) {
  16123. var idx = this._postProcesses.indexOf(postProcess);
  16124. if (idx !== -1) {
  16125. this._postProcesses.splice(idx, 1);
  16126. }
  16127. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16128. };
  16129. Camera.prototype.getWorldMatrix = function () {
  16130. if (!this._worldMatrix) {
  16131. this._worldMatrix = BABYLON.Matrix.Identity();
  16132. }
  16133. var viewMatrix = this.getViewMatrix();
  16134. viewMatrix.invertToRef(this._worldMatrix);
  16135. return this._worldMatrix;
  16136. };
  16137. Camera.prototype._getViewMatrix = function () {
  16138. return BABYLON.Matrix.Identity();
  16139. };
  16140. Camera.prototype.getViewMatrix = function (force) {
  16141. if (!force && this._isSynchronizedViewMatrix()) {
  16142. return this._computedViewMatrix;
  16143. }
  16144. this.updateCache();
  16145. this._computedViewMatrix = this._getViewMatrix();
  16146. this._currentRenderId = this.getScene().getRenderId();
  16147. this._refreshFrustumPlanes = true;
  16148. if (!this.parent || !this.parent.getWorldMatrix) {
  16149. this._globalPosition.copyFrom(this.position);
  16150. }
  16151. else {
  16152. if (!this._worldMatrix) {
  16153. this._worldMatrix = BABYLON.Matrix.Identity();
  16154. }
  16155. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16156. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16157. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16158. this._computedViewMatrix.invert();
  16159. this._markSyncedWithParent();
  16160. }
  16161. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16162. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16163. }
  16164. this.onViewMatrixChangedObservable.notifyObservers(this);
  16165. return this._computedViewMatrix;
  16166. };
  16167. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16168. this._doNotComputeProjectionMatrix = true;
  16169. if (projection !== undefined) {
  16170. this._projectionMatrix = projection;
  16171. }
  16172. };
  16173. ;
  16174. Camera.prototype.unfreezeProjectionMatrix = function () {
  16175. this._doNotComputeProjectionMatrix = false;
  16176. };
  16177. ;
  16178. Camera.prototype.getProjectionMatrix = function (force) {
  16179. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16180. return this._projectionMatrix;
  16181. }
  16182. // Cache
  16183. this._cache.mode = this.mode;
  16184. this._cache.minZ = this.minZ;
  16185. this._cache.maxZ = this.maxZ;
  16186. // Matrix
  16187. this._refreshFrustumPlanes = true;
  16188. var engine = this.getEngine();
  16189. var scene = this.getScene();
  16190. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16191. this._cache.fov = this.fov;
  16192. this._cache.fovMode = this.fovMode;
  16193. this._cache.aspectRatio = engine.getAspectRatio(this);
  16194. if (this.minZ <= 0) {
  16195. this.minZ = 0.1;
  16196. }
  16197. if (scene.useRightHandedSystem) {
  16198. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16199. }
  16200. else {
  16201. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16202. }
  16203. }
  16204. else {
  16205. var halfWidth = engine.getRenderWidth() / 2.0;
  16206. var halfHeight = engine.getRenderHeight() / 2.0;
  16207. if (scene.useRightHandedSystem) {
  16208. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16209. }
  16210. else {
  16211. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16212. }
  16213. this._cache.orthoLeft = this.orthoLeft;
  16214. this._cache.orthoRight = this.orthoRight;
  16215. this._cache.orthoBottom = this.orthoBottom;
  16216. this._cache.orthoTop = this.orthoTop;
  16217. this._cache.renderWidth = engine.getRenderWidth();
  16218. this._cache.renderHeight = engine.getRenderHeight();
  16219. }
  16220. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16221. return this._projectionMatrix;
  16222. };
  16223. Camera.prototype.getTranformationMatrix = function () {
  16224. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16225. return this._transformMatrix;
  16226. };
  16227. Camera.prototype.updateFrustumPlanes = function () {
  16228. if (!this._refreshFrustumPlanes) {
  16229. return;
  16230. }
  16231. this.getTranformationMatrix();
  16232. if (!this._frustumPlanes) {
  16233. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16234. }
  16235. else {
  16236. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16237. }
  16238. this._refreshFrustumPlanes = false;
  16239. };
  16240. Camera.prototype.isInFrustum = function (target) {
  16241. this.updateFrustumPlanes();
  16242. return target.isInFrustum(this._frustumPlanes);
  16243. };
  16244. Camera.prototype.isCompletelyInFrustum = function (target) {
  16245. this.updateFrustumPlanes();
  16246. return target.isCompletelyInFrustum(this._frustumPlanes);
  16247. };
  16248. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16249. if (length === void 0) { length = 100; }
  16250. if (!transform) {
  16251. transform = this.getWorldMatrix();
  16252. }
  16253. if (!origin) {
  16254. origin = this.position;
  16255. }
  16256. var forward = new BABYLON.Vector3(0, 0, 1);
  16257. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16258. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16259. return new BABYLON.Ray(origin, direction, length);
  16260. };
  16261. Camera.prototype.dispose = function () {
  16262. // Observables
  16263. this.onViewMatrixChangedObservable.clear();
  16264. this.onProjectionMatrixChangedObservable.clear();
  16265. this.onAfterCheckInputsObservable.clear();
  16266. this.onRestoreStateObservable.clear();
  16267. // Inputs
  16268. if (this.inputs) {
  16269. this.inputs.clear();
  16270. }
  16271. // Animations
  16272. this.getScene().stopAnimation(this);
  16273. // Remove from scene
  16274. this.getScene().removeCamera(this);
  16275. while (this._rigCameras.length > 0) {
  16276. var camera = this._rigCameras.pop();
  16277. if (camera) {
  16278. camera.dispose();
  16279. }
  16280. }
  16281. // Postprocesses
  16282. if (this._rigPostProcess) {
  16283. this._rigPostProcess.dispose(this);
  16284. this._rigPostProcess = null;
  16285. this._postProcesses = [];
  16286. }
  16287. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16288. this._rigPostProcess = null;
  16289. this._postProcesses = [];
  16290. }
  16291. else {
  16292. var i = this._postProcesses.length;
  16293. while (--i >= 0) {
  16294. this._postProcesses[i].dispose(this);
  16295. }
  16296. }
  16297. // Render targets
  16298. var i = this.customRenderTargets.length;
  16299. while (--i >= 0) {
  16300. this.customRenderTargets[i].dispose();
  16301. }
  16302. this.customRenderTargets = [];
  16303. // Active Meshes
  16304. this._activeMeshes.dispose();
  16305. _super.prototype.dispose.call(this);
  16306. };
  16307. Object.defineProperty(Camera.prototype, "leftCamera", {
  16308. // ---- Camera rigs section ----
  16309. get: function () {
  16310. if (this._rigCameras.length < 1) {
  16311. return null;
  16312. }
  16313. return this._rigCameras[0];
  16314. },
  16315. enumerable: true,
  16316. configurable: true
  16317. });
  16318. Object.defineProperty(Camera.prototype, "rightCamera", {
  16319. get: function () {
  16320. if (this._rigCameras.length < 2) {
  16321. return null;
  16322. }
  16323. return this._rigCameras[1];
  16324. },
  16325. enumerable: true,
  16326. configurable: true
  16327. });
  16328. Camera.prototype.getLeftTarget = function () {
  16329. if (this._rigCameras.length < 1) {
  16330. return null;
  16331. }
  16332. return this._rigCameras[0].getTarget();
  16333. };
  16334. Camera.prototype.getRightTarget = function () {
  16335. if (this._rigCameras.length < 2) {
  16336. return null;
  16337. }
  16338. return this._rigCameras[1].getTarget();
  16339. };
  16340. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16341. if (this.cameraRigMode === mode) {
  16342. return;
  16343. }
  16344. while (this._rigCameras.length > 0) {
  16345. var camera = this._rigCameras.pop();
  16346. if (camera) {
  16347. camera.dispose();
  16348. }
  16349. }
  16350. this.cameraRigMode = mode;
  16351. this._cameraRigParams = {};
  16352. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16353. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16354. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16355. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16356. // create the rig cameras, unless none
  16357. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16358. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16359. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16360. if (leftCamera && rightCamera) {
  16361. this._rigCameras.push(leftCamera);
  16362. this._rigCameras.push(rightCamera);
  16363. }
  16364. }
  16365. switch (this.cameraRigMode) {
  16366. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16367. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16368. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16369. break;
  16370. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16371. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16372. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16373. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16374. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16375. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16376. break;
  16377. case Camera.RIG_MODE_VR:
  16378. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16379. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16380. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16381. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16382. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16383. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16384. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16385. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16386. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16387. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16388. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16389. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16390. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16391. if (metrics.compensateDistortion) {
  16392. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16393. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16394. }
  16395. break;
  16396. case Camera.RIG_MODE_WEBVR:
  16397. if (rigParams.vrDisplay) {
  16398. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16399. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16400. //Left eye
  16401. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16402. this._rigCameras[0].setCameraRigParameter("left", true);
  16403. //leaving this for future reference
  16404. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16405. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16406. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16407. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16408. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16409. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16410. this._rigCameras[0].parent = this;
  16411. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16412. //Right eye
  16413. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16414. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16415. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16416. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16417. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16418. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16419. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16420. this._rigCameras[1].parent = this;
  16421. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16422. if (Camera.UseAlternateWebVRRendering) {
  16423. this._rigCameras[1]._skipRendering = true;
  16424. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16425. }
  16426. }
  16427. break;
  16428. }
  16429. this._cascadePostProcessesToRigCams();
  16430. this.update();
  16431. };
  16432. Camera.prototype._getVRProjectionMatrix = function () {
  16433. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16434. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16435. return this._projectionMatrix;
  16436. };
  16437. Camera.prototype._updateCameraRotationMatrix = function () {
  16438. //Here for WebVR
  16439. };
  16440. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16441. //Here for WebVR
  16442. };
  16443. /**
  16444. * This function MUST be overwritten by the different WebVR cameras available.
  16445. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16446. */
  16447. Camera.prototype._getWebVRProjectionMatrix = function () {
  16448. return BABYLON.Matrix.Identity();
  16449. };
  16450. /**
  16451. * This function MUST be overwritten by the different WebVR cameras available.
  16452. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16453. */
  16454. Camera.prototype._getWebVRViewMatrix = function () {
  16455. return BABYLON.Matrix.Identity();
  16456. };
  16457. Camera.prototype.setCameraRigParameter = function (name, value) {
  16458. if (!this._cameraRigParams) {
  16459. this._cameraRigParams = {};
  16460. }
  16461. this._cameraRigParams[name] = value;
  16462. //provisionnally:
  16463. if (name === "interaxialDistance") {
  16464. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16465. }
  16466. };
  16467. /**
  16468. * needs to be overridden by children so sub has required properties to be copied
  16469. */
  16470. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16471. return null;
  16472. };
  16473. /**
  16474. * May need to be overridden by children
  16475. */
  16476. Camera.prototype._updateRigCameras = function () {
  16477. for (var i = 0; i < this._rigCameras.length; i++) {
  16478. this._rigCameras[i].minZ = this.minZ;
  16479. this._rigCameras[i].maxZ = this.maxZ;
  16480. this._rigCameras[i].fov = this.fov;
  16481. }
  16482. // only update viewport when ANAGLYPH
  16483. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16484. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16485. }
  16486. };
  16487. Camera.prototype._setupInputs = function () {
  16488. };
  16489. Camera.prototype.serialize = function () {
  16490. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16491. // Type
  16492. serializationObject.type = this.getClassName();
  16493. // Parent
  16494. if (this.parent) {
  16495. serializationObject.parentId = this.parent.id;
  16496. }
  16497. if (this.inputs) {
  16498. this.inputs.serialize(serializationObject);
  16499. }
  16500. // Animations
  16501. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16502. serializationObject.ranges = this.serializeAnimationRanges();
  16503. return serializationObject;
  16504. };
  16505. Camera.prototype.clone = function (name) {
  16506. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16507. };
  16508. Camera.prototype.getDirection = function (localAxis) {
  16509. var result = BABYLON.Vector3.Zero();
  16510. this.getDirectionToRef(localAxis, result);
  16511. return result;
  16512. };
  16513. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16514. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16515. };
  16516. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16517. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16518. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16519. switch (type) {
  16520. case "ArcRotateCamera":
  16521. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16522. case "DeviceOrientationCamera":
  16523. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16524. case "FollowCamera":
  16525. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16526. case "ArcFollowCamera":
  16527. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16528. case "GamepadCamera":
  16529. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16530. case "TouchCamera":
  16531. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16532. case "VirtualJoysticksCamera":
  16533. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16534. case "WebVRFreeCamera":
  16535. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16536. case "WebVRGamepadCamera":
  16537. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16538. case "VRDeviceOrientationFreeCamera":
  16539. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16540. case "VRDeviceOrientationGamepadCamera":
  16541. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16542. case "AnaglyphArcRotateCamera":
  16543. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16544. case "AnaglyphFreeCamera":
  16545. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16546. case "AnaglyphGamepadCamera":
  16547. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16548. case "AnaglyphUniversalCamera":
  16549. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16550. case "StereoscopicArcRotateCamera":
  16551. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16552. case "StereoscopicFreeCamera":
  16553. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16554. case "StereoscopicGamepadCamera":
  16555. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16556. case "StereoscopicUniversalCamera":
  16557. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16558. case "FreeCamera":// Forcing Universal here
  16559. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16560. default:// Universal Camera is the default value
  16561. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16562. }
  16563. };
  16564. Camera.Parse = function (parsedCamera, scene) {
  16565. var type = parsedCamera.type;
  16566. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16567. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16568. // Parent
  16569. if (parsedCamera.parentId) {
  16570. camera._waitingParentId = parsedCamera.parentId;
  16571. }
  16572. //If camera has an input manager, let it parse inputs settings
  16573. if (camera.inputs) {
  16574. camera.inputs.parse(parsedCamera);
  16575. camera._setupInputs();
  16576. }
  16577. if (camera.setPosition) {
  16578. camera.position.copyFromFloats(0, 0, 0);
  16579. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16580. }
  16581. // Target
  16582. if (parsedCamera.target) {
  16583. if (camera.setTarget) {
  16584. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16585. }
  16586. }
  16587. // Apply 3d rig, when found
  16588. if (parsedCamera.cameraRigMode) {
  16589. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16590. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16591. }
  16592. // Animations
  16593. if (parsedCamera.animations) {
  16594. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16595. var parsedAnimation = parsedCamera.animations[animationIndex];
  16596. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16597. }
  16598. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16599. }
  16600. if (parsedCamera.autoAnimate) {
  16601. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16602. }
  16603. return camera;
  16604. };
  16605. // Statics
  16606. Camera._PERSPECTIVE_CAMERA = 0;
  16607. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16608. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16609. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16610. Camera._RIG_MODE_NONE = 0;
  16611. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16612. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16613. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16614. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16615. Camera._RIG_MODE_VR = 20;
  16616. Camera._RIG_MODE_WEBVR = 21;
  16617. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16618. Camera.UseAlternateWebVRRendering = false;
  16619. __decorate([
  16620. BABYLON.serializeAsVector3()
  16621. ], Camera.prototype, "position", void 0);
  16622. __decorate([
  16623. BABYLON.serializeAsVector3()
  16624. ], Camera.prototype, "upVector", void 0);
  16625. __decorate([
  16626. BABYLON.serialize()
  16627. ], Camera.prototype, "orthoLeft", void 0);
  16628. __decorate([
  16629. BABYLON.serialize()
  16630. ], Camera.prototype, "orthoRight", void 0);
  16631. __decorate([
  16632. BABYLON.serialize()
  16633. ], Camera.prototype, "orthoBottom", void 0);
  16634. __decorate([
  16635. BABYLON.serialize()
  16636. ], Camera.prototype, "orthoTop", void 0);
  16637. __decorate([
  16638. BABYLON.serialize()
  16639. ], Camera.prototype, "fov", void 0);
  16640. __decorate([
  16641. BABYLON.serialize()
  16642. ], Camera.prototype, "minZ", void 0);
  16643. __decorate([
  16644. BABYLON.serialize()
  16645. ], Camera.prototype, "maxZ", void 0);
  16646. __decorate([
  16647. BABYLON.serialize()
  16648. ], Camera.prototype, "inertia", void 0);
  16649. __decorate([
  16650. BABYLON.serialize()
  16651. ], Camera.prototype, "mode", void 0);
  16652. __decorate([
  16653. BABYLON.serialize()
  16654. ], Camera.prototype, "layerMask", void 0);
  16655. __decorate([
  16656. BABYLON.serialize()
  16657. ], Camera.prototype, "fovMode", void 0);
  16658. __decorate([
  16659. BABYLON.serialize()
  16660. ], Camera.prototype, "cameraRigMode", void 0);
  16661. __decorate([
  16662. BABYLON.serialize()
  16663. ], Camera.prototype, "interaxialDistance", void 0);
  16664. __decorate([
  16665. BABYLON.serialize()
  16666. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16667. return Camera;
  16668. }(BABYLON.Node));
  16669. BABYLON.Camera = Camera;
  16670. })(BABYLON || (BABYLON = {}));
  16671. //# sourceMappingURL=babylon.camera.js.map
  16672. var BABYLON;
  16673. (function (BABYLON) {
  16674. var RenderingManager = /** @class */ (function () {
  16675. function RenderingManager(scene) {
  16676. this._renderingGroups = new Array();
  16677. this._autoClearDepthStencil = {};
  16678. this._customOpaqueSortCompareFn = {};
  16679. this._customAlphaTestSortCompareFn = {};
  16680. this._customTransparentSortCompareFn = {};
  16681. this._renderinGroupInfo = null;
  16682. this._scene = scene;
  16683. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16684. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16685. }
  16686. }
  16687. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16688. if (depth === void 0) { depth = true; }
  16689. if (stencil === void 0) { stencil = true; }
  16690. if (this._depthStencilBufferAlreadyCleaned) {
  16691. return;
  16692. }
  16693. this._scene.getEngine().clear(null, false, depth, stencil);
  16694. this._depthStencilBufferAlreadyCleaned = true;
  16695. };
  16696. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16697. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16698. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16699. var info = null;
  16700. if (observable) {
  16701. if (!this._renderinGroupInfo) {
  16702. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16703. }
  16704. info = this._renderinGroupInfo;
  16705. info.scene = this._scene;
  16706. info.camera = this._scene.activeCamera;
  16707. }
  16708. // Dispatch sprites
  16709. if (renderSprites) {
  16710. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16711. var manager = this._scene.spriteManagers[index];
  16712. this.dispatchSprites(manager);
  16713. }
  16714. }
  16715. // Render
  16716. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16717. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16718. var renderingGroup = this._renderingGroups[index];
  16719. if (!renderingGroup && !observable)
  16720. continue;
  16721. this._currentIndex = index;
  16722. var renderingGroupMask = 0;
  16723. // Fire PRECLEAR stage
  16724. if (observable && info) {
  16725. renderingGroupMask = Math.pow(2, index);
  16726. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16727. info.renderingGroupId = index;
  16728. observable.notifyObservers(info, renderingGroupMask);
  16729. }
  16730. // Clear depth/stencil if needed
  16731. if (RenderingManager.AUTOCLEAR) {
  16732. var autoClear = this._autoClearDepthStencil[index];
  16733. if (autoClear && autoClear.autoClear) {
  16734. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16735. }
  16736. }
  16737. if (observable && info) {
  16738. // Fire PREOPAQUE stage
  16739. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16740. observable.notifyObservers(info, renderingGroupMask);
  16741. // Fire PRETRANSPARENT stage
  16742. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16743. observable.notifyObservers(info, renderingGroupMask);
  16744. }
  16745. if (renderingGroup)
  16746. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16747. // Fire POSTTRANSPARENT stage
  16748. if (observable && info) {
  16749. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16750. observable.notifyObservers(info, renderingGroupMask);
  16751. }
  16752. }
  16753. };
  16754. RenderingManager.prototype.reset = function () {
  16755. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16756. var renderingGroup = this._renderingGroups[index];
  16757. if (renderingGroup) {
  16758. renderingGroup.prepare();
  16759. }
  16760. }
  16761. };
  16762. RenderingManager.prototype.dispose = function () {
  16763. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16764. var renderingGroup = this._renderingGroups[index];
  16765. if (renderingGroup) {
  16766. renderingGroup.dispose();
  16767. }
  16768. }
  16769. this._renderingGroups.length = 0;
  16770. };
  16771. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16772. if (!this._renderingGroups[renderingGroupId]) {
  16773. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16774. }
  16775. };
  16776. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16777. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16778. this._prepareRenderingGroup(renderingGroupId);
  16779. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16780. };
  16781. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16782. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16783. this._prepareRenderingGroup(renderingGroupId);
  16784. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16785. };
  16786. RenderingManager.prototype.dispatch = function (subMesh) {
  16787. var mesh = subMesh.getMesh();
  16788. var renderingGroupId = mesh.renderingGroupId || 0;
  16789. this._prepareRenderingGroup(renderingGroupId);
  16790. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16791. };
  16792. /**
  16793. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16794. * This allowed control for front to back rendering or reversly depending of the special needs.
  16795. *
  16796. * @param renderingGroupId The rendering group id corresponding to its index
  16797. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16798. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16799. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16800. */
  16801. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16802. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16803. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16804. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16805. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16806. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16807. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16808. if (this._renderingGroups[renderingGroupId]) {
  16809. var group = this._renderingGroups[renderingGroupId];
  16810. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16811. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16812. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16813. }
  16814. };
  16815. /**
  16816. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16817. *
  16818. * @param renderingGroupId The rendering group id corresponding to its index
  16819. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16820. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16821. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16822. */
  16823. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16824. if (depth === void 0) { depth = true; }
  16825. if (stencil === void 0) { stencil = true; }
  16826. this._autoClearDepthStencil[renderingGroupId] = {
  16827. autoClear: autoClearDepthStencil,
  16828. depth: depth,
  16829. stencil: stencil
  16830. };
  16831. };
  16832. /**
  16833. * The max id used for rendering groups (not included)
  16834. */
  16835. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16836. /**
  16837. * The min id used for rendering groups (included)
  16838. */
  16839. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16840. /**
  16841. * Used to globally prevent autoclearing scenes.
  16842. */
  16843. RenderingManager.AUTOCLEAR = true;
  16844. return RenderingManager;
  16845. }());
  16846. BABYLON.RenderingManager = RenderingManager;
  16847. })(BABYLON || (BABYLON = {}));
  16848. //# sourceMappingURL=babylon.renderingManager.js.map
  16849. var BABYLON;
  16850. (function (BABYLON) {
  16851. var RenderingGroup = /** @class */ (function () {
  16852. /**
  16853. * Creates a new rendering group.
  16854. * @param index The rendering group index
  16855. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16856. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16857. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16858. */
  16859. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16860. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16861. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16862. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16863. this.index = index;
  16864. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16865. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16866. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16867. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16868. this._particleSystems = new BABYLON.SmartArray(256);
  16869. this._spriteManagers = new BABYLON.SmartArray(256);
  16870. this._edgesRenderers = new BABYLON.SmartArray(16);
  16871. this._scene = scene;
  16872. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16873. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16874. this.transparentSortCompareFn = transparentSortCompareFn;
  16875. }
  16876. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16877. /**
  16878. * Set the opaque sort comparison function.
  16879. * If null the sub meshes will be render in the order they were created
  16880. */
  16881. set: function (value) {
  16882. this._opaqueSortCompareFn = value;
  16883. if (value) {
  16884. this._renderOpaque = this.renderOpaqueSorted;
  16885. }
  16886. else {
  16887. this._renderOpaque = RenderingGroup.renderUnsorted;
  16888. }
  16889. },
  16890. enumerable: true,
  16891. configurable: true
  16892. });
  16893. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16894. /**
  16895. * Set the alpha test sort comparison function.
  16896. * If null the sub meshes will be render in the order they were created
  16897. */
  16898. set: function (value) {
  16899. this._alphaTestSortCompareFn = value;
  16900. if (value) {
  16901. this._renderAlphaTest = this.renderAlphaTestSorted;
  16902. }
  16903. else {
  16904. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16905. }
  16906. },
  16907. enumerable: true,
  16908. configurable: true
  16909. });
  16910. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16911. /**
  16912. * Set the transparent sort comparison function.
  16913. * If null the sub meshes will be render in the order they were created
  16914. */
  16915. set: function (value) {
  16916. if (value) {
  16917. this._transparentSortCompareFn = value;
  16918. }
  16919. else {
  16920. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16921. }
  16922. this._renderTransparent = this.renderTransparentSorted;
  16923. },
  16924. enumerable: true,
  16925. configurable: true
  16926. });
  16927. /**
  16928. * Render all the sub meshes contained in the group.
  16929. * @param customRenderFunction Used to override the default render behaviour of the group.
  16930. * @returns true if rendered some submeshes.
  16931. */
  16932. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16933. if (customRenderFunction) {
  16934. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16935. return;
  16936. }
  16937. var engine = this._scene.getEngine();
  16938. // Depth only
  16939. if (this._depthOnlySubMeshes.length !== 0) {
  16940. engine.setAlphaTesting(true);
  16941. engine.setColorWrite(false);
  16942. this._renderAlphaTest(this._depthOnlySubMeshes);
  16943. engine.setAlphaTesting(false);
  16944. engine.setColorWrite(true);
  16945. }
  16946. // Opaque
  16947. if (this._opaqueSubMeshes.length !== 0) {
  16948. this._renderOpaque(this._opaqueSubMeshes);
  16949. }
  16950. // Alpha test
  16951. if (this._alphaTestSubMeshes.length !== 0) {
  16952. engine.setAlphaTesting(true);
  16953. this._renderAlphaTest(this._alphaTestSubMeshes);
  16954. engine.setAlphaTesting(false);
  16955. }
  16956. var stencilState = engine.getStencilBuffer();
  16957. engine.setStencilBuffer(false);
  16958. // Sprites
  16959. if (renderSprites) {
  16960. this._renderSprites();
  16961. }
  16962. // Particles
  16963. if (renderParticles) {
  16964. this._renderParticles(activeMeshes);
  16965. }
  16966. if (this.onBeforeTransparentRendering) {
  16967. this.onBeforeTransparentRendering();
  16968. }
  16969. // Transparent
  16970. if (this._transparentSubMeshes.length !== 0) {
  16971. this._renderTransparent(this._transparentSubMeshes);
  16972. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16973. }
  16974. // Set back stencil to false in case it changes before the edge renderer.
  16975. engine.setStencilBuffer(false);
  16976. // Edges
  16977. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16978. this._edgesRenderers.data[edgesRendererIndex].render();
  16979. }
  16980. // Restore Stencil state.
  16981. engine.setStencilBuffer(stencilState);
  16982. };
  16983. /**
  16984. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16985. * @param subMeshes The submeshes to render
  16986. */
  16987. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16988. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  16989. };
  16990. /**
  16991. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16992. * @param subMeshes The submeshes to render
  16993. */
  16994. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16995. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  16996. };
  16997. /**
  16998. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16999. * @param subMeshes The submeshes to render
  17000. */
  17001. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17002. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17003. };
  17004. /**
  17005. * Renders the submeshes in a specified order.
  17006. * @param subMeshes The submeshes to sort before render
  17007. * @param sortCompareFn The comparison function use to sort
  17008. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17009. * @param transparent Specifies to activate blending if true
  17010. */
  17011. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17012. var subIndex = 0;
  17013. var subMesh;
  17014. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17015. for (; subIndex < subMeshes.length; subIndex++) {
  17016. subMesh = subMeshes.data[subIndex];
  17017. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17018. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17019. }
  17020. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17021. if (sortCompareFn) {
  17022. sortedArray.sort(sortCompareFn);
  17023. }
  17024. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17025. subMesh = sortedArray[subIndex];
  17026. if (transparent) {
  17027. var material = subMesh.getMaterial();
  17028. if (material && material.needDepthPrePass) {
  17029. var engine = material.getScene().getEngine();
  17030. engine.setColorWrite(false);
  17031. engine.setAlphaTesting(true);
  17032. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17033. subMesh.render(false);
  17034. engine.setAlphaTesting(false);
  17035. engine.setColorWrite(true);
  17036. }
  17037. }
  17038. subMesh.render(transparent);
  17039. }
  17040. };
  17041. /**
  17042. * Renders the submeshes in the order they were dispatched (no sort applied).
  17043. * @param subMeshes The submeshes to render
  17044. */
  17045. RenderingGroup.renderUnsorted = function (subMeshes) {
  17046. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17047. var submesh = subMeshes.data[subIndex];
  17048. submesh.render(false);
  17049. }
  17050. };
  17051. /**
  17052. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17053. * are rendered back to front if in the same alpha index.
  17054. *
  17055. * @param a The first submesh
  17056. * @param b The second submesh
  17057. * @returns The result of the comparison
  17058. */
  17059. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17060. // Alpha index first
  17061. if (a._alphaIndex > b._alphaIndex) {
  17062. return 1;
  17063. }
  17064. if (a._alphaIndex < b._alphaIndex) {
  17065. return -1;
  17066. }
  17067. // Then distance to camera
  17068. return RenderingGroup.backToFrontSortCompare(a, b);
  17069. };
  17070. /**
  17071. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17072. * are rendered back to front.
  17073. *
  17074. * @param a The first submesh
  17075. * @param b The second submesh
  17076. * @returns The result of the comparison
  17077. */
  17078. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17079. // Then distance to camera
  17080. if (a._distanceToCamera < b._distanceToCamera) {
  17081. return 1;
  17082. }
  17083. if (a._distanceToCamera > b._distanceToCamera) {
  17084. return -1;
  17085. }
  17086. return 0;
  17087. };
  17088. /**
  17089. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17090. * are rendered front to back (prevent overdraw).
  17091. *
  17092. * @param a The first submesh
  17093. * @param b The second submesh
  17094. * @returns The result of the comparison
  17095. */
  17096. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17097. // Then distance to camera
  17098. if (a._distanceToCamera < b._distanceToCamera) {
  17099. return -1;
  17100. }
  17101. if (a._distanceToCamera > b._distanceToCamera) {
  17102. return 1;
  17103. }
  17104. return 0;
  17105. };
  17106. /**
  17107. * Resets the different lists of submeshes to prepare a new frame.
  17108. */
  17109. RenderingGroup.prototype.prepare = function () {
  17110. this._opaqueSubMeshes.reset();
  17111. this._transparentSubMeshes.reset();
  17112. this._alphaTestSubMeshes.reset();
  17113. this._depthOnlySubMeshes.reset();
  17114. this._particleSystems.reset();
  17115. this._spriteManagers.reset();
  17116. this._edgesRenderers.reset();
  17117. };
  17118. RenderingGroup.prototype.dispose = function () {
  17119. this._opaqueSubMeshes.dispose();
  17120. this._transparentSubMeshes.dispose();
  17121. this._alphaTestSubMeshes.dispose();
  17122. this._depthOnlySubMeshes.dispose();
  17123. this._particleSystems.dispose();
  17124. this._spriteManagers.dispose();
  17125. this._edgesRenderers.dispose();
  17126. };
  17127. /**
  17128. * Inserts the submesh in its correct queue depending on its material.
  17129. * @param subMesh The submesh to dispatch
  17130. */
  17131. RenderingGroup.prototype.dispatch = function (subMesh) {
  17132. var material = subMesh.getMaterial();
  17133. var mesh = subMesh.getMesh();
  17134. if (!material) {
  17135. return;
  17136. }
  17137. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  17138. this._transparentSubMeshes.push(subMesh);
  17139. }
  17140. else if (material.needAlphaTesting()) {
  17141. if (material.needDepthPrePass) {
  17142. this._depthOnlySubMeshes.push(subMesh);
  17143. }
  17144. this._alphaTestSubMeshes.push(subMesh);
  17145. }
  17146. else {
  17147. if (material.needDepthPrePass) {
  17148. this._depthOnlySubMeshes.push(subMesh);
  17149. }
  17150. this._opaqueSubMeshes.push(subMesh); // Opaque
  17151. }
  17152. if (mesh._edgesRenderer) {
  17153. this._edgesRenderers.push(mesh._edgesRenderer);
  17154. }
  17155. };
  17156. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17157. this._spriteManagers.push(spriteManager);
  17158. };
  17159. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17160. this._particleSystems.push(particleSystem);
  17161. };
  17162. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17163. if (this._particleSystems.length === 0) {
  17164. return;
  17165. }
  17166. // Particles
  17167. var activeCamera = this._scene.activeCamera;
  17168. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17169. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17170. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17171. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17172. continue;
  17173. }
  17174. var emitter = particleSystem.emitter;
  17175. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17176. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17177. }
  17178. }
  17179. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17180. };
  17181. RenderingGroup.prototype._renderSprites = function () {
  17182. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17183. return;
  17184. }
  17185. // Sprites
  17186. var activeCamera = this._scene.activeCamera;
  17187. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17188. for (var id = 0; id < this._spriteManagers.length; id++) {
  17189. var spriteManager = this._spriteManagers.data[id];
  17190. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17191. spriteManager.render();
  17192. }
  17193. }
  17194. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17195. };
  17196. return RenderingGroup;
  17197. }());
  17198. BABYLON.RenderingGroup = RenderingGroup;
  17199. })(BABYLON || (BABYLON = {}));
  17200. //# sourceMappingURL=babylon.renderingGroup.js.map
  17201. var BABYLON;
  17202. (function (BABYLON) {
  17203. var ClickInfo = /** @class */ (function () {
  17204. function ClickInfo() {
  17205. this._singleClick = false;
  17206. this._doubleClick = false;
  17207. this._hasSwiped = false;
  17208. this._ignore = false;
  17209. }
  17210. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17211. get: function () {
  17212. return this._singleClick;
  17213. },
  17214. set: function (b) {
  17215. this._singleClick = b;
  17216. },
  17217. enumerable: true,
  17218. configurable: true
  17219. });
  17220. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17221. get: function () {
  17222. return this._doubleClick;
  17223. },
  17224. set: function (b) {
  17225. this._doubleClick = b;
  17226. },
  17227. enumerable: true,
  17228. configurable: true
  17229. });
  17230. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17231. get: function () {
  17232. return this._hasSwiped;
  17233. },
  17234. set: function (b) {
  17235. this._hasSwiped = b;
  17236. },
  17237. enumerable: true,
  17238. configurable: true
  17239. });
  17240. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17241. get: function () {
  17242. return this._ignore;
  17243. },
  17244. set: function (b) {
  17245. this._ignore = b;
  17246. },
  17247. enumerable: true,
  17248. configurable: true
  17249. });
  17250. return ClickInfo;
  17251. }());
  17252. /**
  17253. * This class is used by the onRenderingGroupObservable
  17254. */
  17255. var RenderingGroupInfo = /** @class */ (function () {
  17256. function RenderingGroupInfo() {
  17257. }
  17258. /**
  17259. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17260. * This stage will be fired no matter what
  17261. */
  17262. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17263. /**
  17264. * Called before opaque object are rendered.
  17265. * This stage will be fired only if there's 3D Opaque content to render
  17266. */
  17267. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17268. /**
  17269. * Called after the opaque objects are rendered and before the transparent ones
  17270. * This stage will be fired only if there's 3D transparent content to render
  17271. */
  17272. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17273. /**
  17274. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17275. * This stage will be fired no matter what
  17276. */
  17277. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17278. return RenderingGroupInfo;
  17279. }());
  17280. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17281. /**
  17282. * Represents a scene to be rendered by the engine.
  17283. * @see http://doc.babylonjs.com/page.php?p=21911
  17284. */
  17285. var Scene = /** @class */ (function () {
  17286. /**
  17287. * @constructor
  17288. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17289. */
  17290. function Scene(engine) {
  17291. // Members
  17292. this.autoClear = true;
  17293. this.autoClearDepthAndStencil = true;
  17294. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17295. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17296. this.forceWireframe = false;
  17297. this._forcePointsCloud = false;
  17298. this.forceShowBoundingBoxes = false;
  17299. this.animationsEnabled = true;
  17300. this.constantlyUpdateMeshUnderPointer = false;
  17301. this.hoverCursor = "pointer";
  17302. this.defaultCursor = "";
  17303. /**
  17304. * This is used to call preventDefault() on pointer down
  17305. * in order to block unwanted artifacts like system double clicks
  17306. */
  17307. this.preventDefaultOnPointerDown = true;
  17308. // Metadata
  17309. this.metadata = null;
  17310. /**
  17311. * An event triggered when the scene is disposed.
  17312. * @type {BABYLON.Observable}
  17313. */
  17314. this.onDisposeObservable = new BABYLON.Observable();
  17315. /**
  17316. * An event triggered before rendering the scene (right after animations and physics)
  17317. * @type {BABYLON.Observable}
  17318. */
  17319. this.onBeforeRenderObservable = new BABYLON.Observable();
  17320. /**
  17321. * An event triggered after rendering the scene
  17322. * @type {BABYLON.Observable}
  17323. */
  17324. this.onAfterRenderObservable = new BABYLON.Observable();
  17325. /**
  17326. * An event triggered before animating the scene
  17327. * @type {BABYLON.Observable}
  17328. */
  17329. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17330. /**
  17331. * An event triggered after animations processing
  17332. * @type {BABYLON.Observable}
  17333. */
  17334. this.onAfterAnimationsObservable = new BABYLON.Observable();
  17335. /**
  17336. * An event triggered before draw calls are ready to be sent
  17337. * @type {BABYLON.Observable}
  17338. */
  17339. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17340. /**
  17341. * An event triggered after draw calls have been sent
  17342. * @type {BABYLON.Observable}
  17343. */
  17344. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17345. /**
  17346. * An event triggered when physic simulation is about to be run
  17347. * @type {BABYLON.Observable}
  17348. */
  17349. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17350. /**
  17351. * An event triggered when physic simulation has been done
  17352. * @type {BABYLON.Observable}
  17353. */
  17354. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17355. /**
  17356. * An event triggered when the scene is ready
  17357. * @type {BABYLON.Observable}
  17358. */
  17359. this.onReadyObservable = new BABYLON.Observable();
  17360. /**
  17361. * An event triggered before rendering a camera
  17362. * @type {BABYLON.Observable}
  17363. */
  17364. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17365. /**
  17366. * An event triggered after rendering a camera
  17367. * @type {BABYLON.Observable}
  17368. */
  17369. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17370. /**
  17371. * An event triggered when active meshes evaluation is about to start
  17372. * @type {BABYLON.Observable}
  17373. */
  17374. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17375. /**
  17376. * An event triggered when active meshes evaluation is done
  17377. * @type {BABYLON.Observable}
  17378. */
  17379. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17380. /**
  17381. * An event triggered when particles rendering is about to start
  17382. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17383. * @type {BABYLON.Observable}
  17384. */
  17385. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17386. /**
  17387. * An event triggered when particles rendering is done
  17388. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17389. * @type {BABYLON.Observable}
  17390. */
  17391. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17392. /**
  17393. * An event triggered when sprites rendering is about to start
  17394. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17395. * @type {BABYLON.Observable}
  17396. */
  17397. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17398. /**
  17399. * An event triggered when sprites rendering is done
  17400. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17401. * @type {BABYLON.Observable}
  17402. */
  17403. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17404. /**
  17405. * An event triggered when a camera is created
  17406. * @type {BABYLON.Observable}
  17407. */
  17408. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17409. /**
  17410. * An event triggered when a camera is removed
  17411. * @type {BABYLON.Observable}
  17412. */
  17413. this.onCameraRemovedObservable = new BABYLON.Observable();
  17414. /**
  17415. * An event triggered when a light is created
  17416. * @type {BABYLON.Observable}
  17417. */
  17418. this.onNewLightAddedObservable = new BABYLON.Observable();
  17419. /**
  17420. * An event triggered when a light is removed
  17421. * @type {BABYLON.Observable}
  17422. */
  17423. this.onLightRemovedObservable = new BABYLON.Observable();
  17424. /**
  17425. * An event triggered when a geometry is created
  17426. * @type {BABYLON.Observable}
  17427. */
  17428. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17429. /**
  17430. * An event triggered when a geometry is removed
  17431. * @type {BABYLON.Observable}
  17432. */
  17433. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17434. /**
  17435. * An event triggered when a mesh is created
  17436. * @type {BABYLON.Observable}
  17437. */
  17438. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17439. /**
  17440. * An event triggered when a mesh is removed
  17441. * @type {BABYLON.Observable}
  17442. */
  17443. this.onMeshRemovedObservable = new BABYLON.Observable();
  17444. /**
  17445. * An event triggered when render targets are about to be rendered
  17446. * Can happen multiple times per frame.
  17447. * @type {BABYLON.Observable}
  17448. */
  17449. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17450. /**
  17451. * An event triggered when render targets were rendered.
  17452. * Can happen multiple times per frame.
  17453. * @type {BABYLON.Observable}
  17454. */
  17455. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17456. /**
  17457. * An event triggered before calculating deterministic simulation step
  17458. * @type {BABYLON.Observable}
  17459. */
  17460. this.onBeforeStepObservable = new BABYLON.Observable();
  17461. /**
  17462. * An event triggered after calculating deterministic simulation step
  17463. * @type {BABYLON.Observable}
  17464. */
  17465. this.onAfterStepObservable = new BABYLON.Observable();
  17466. /**
  17467. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17468. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17469. * 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)
  17470. */
  17471. this.onRenderingGroupObservable = new BABYLON.Observable();
  17472. // Animations
  17473. this.animations = [];
  17474. /**
  17475. * 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).
  17476. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17477. */
  17478. this.onPrePointerObservable = new BABYLON.Observable();
  17479. /**
  17480. * Observable event triggered each time an input event is received from the rendering canvas
  17481. */
  17482. this.onPointerObservable = new BABYLON.Observable();
  17483. this._meshPickProceed = false;
  17484. this._previousHasSwiped = false;
  17485. this._currentPickResult = null;
  17486. this._previousPickResult = null;
  17487. this._totalPointersPressed = 0;
  17488. this._doubleClickOccured = false;
  17489. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17490. this.cameraToUseForPointers = null;
  17491. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17492. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17493. this._startingPointerTime = 0;
  17494. this._previousStartingPointerTime = 0;
  17495. // Deterministic lockstep
  17496. this._timeAccumulator = 0;
  17497. this._currentStepId = 0;
  17498. this._currentInternalStep = 0;
  17499. // Keyboard
  17500. /**
  17501. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17502. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17503. */
  17504. this.onPreKeyboardObservable = new BABYLON.Observable();
  17505. /**
  17506. * Observable event triggered each time an keyboard event is received from the hosting window
  17507. */
  17508. this.onKeyboardObservable = new BABYLON.Observable();
  17509. // Coordinate system
  17510. /**
  17511. * use right-handed coordinate system on this scene.
  17512. * @type {boolean}
  17513. */
  17514. this._useRightHandedSystem = false;
  17515. // Fog
  17516. this._fogEnabled = true;
  17517. this._fogMode = Scene.FOGMODE_NONE;
  17518. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17519. this.fogDensity = 0.1;
  17520. this.fogStart = 0;
  17521. this.fogEnd = 1000.0;
  17522. // Lights
  17523. /**
  17524. * is shadow enabled on this scene.
  17525. * @type {boolean}
  17526. */
  17527. this._shadowsEnabled = true;
  17528. /**
  17529. * is light enabled on this scene.
  17530. * @type {boolean}
  17531. */
  17532. this._lightsEnabled = true;
  17533. /**
  17534. * All of the lights added to this scene.
  17535. * @see BABYLON.Light
  17536. * @type {BABYLON.Light[]}
  17537. */
  17538. this.lights = new Array();
  17539. // Cameras
  17540. /** All of the cameras added to this scene. */
  17541. this.cameras = new Array();
  17542. /** All of the active cameras added to this scene. */
  17543. this.activeCameras = new Array();
  17544. // Meshes
  17545. /**
  17546. * All of the (abstract) meshes added to this scene.
  17547. * @see BABYLON.AbstractMesh
  17548. * @type {BABYLON.AbstractMesh[]}
  17549. */
  17550. this.meshes = new Array();
  17551. // Geometries
  17552. this._geometries = new Array();
  17553. this.materials = new Array();
  17554. this.multiMaterials = new Array();
  17555. // Textures
  17556. this._texturesEnabled = true;
  17557. this.textures = new Array();
  17558. // Particles
  17559. this.particlesEnabled = true;
  17560. this.particleSystems = new Array();
  17561. // Sprites
  17562. this.spritesEnabled = true;
  17563. this.spriteManagers = new Array();
  17564. // Layers
  17565. this.layers = new Array();
  17566. this.highlightLayers = new Array();
  17567. // Skeletons
  17568. this._skeletonsEnabled = true;
  17569. this.skeletons = new Array();
  17570. // Morph targets
  17571. this.morphTargetManagers = new Array();
  17572. // Lens flares
  17573. this.lensFlaresEnabled = true;
  17574. this.lensFlareSystems = new Array();
  17575. // Collisions
  17576. this.collisionsEnabled = true;
  17577. /** Defines the gravity applied to this scene */
  17578. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17579. // Postprocesses
  17580. this.postProcesses = new Array();
  17581. this.postProcessesEnabled = true;
  17582. // Customs render targets
  17583. this.renderTargetsEnabled = true;
  17584. this.dumpNextRenderTargets = false;
  17585. this.customRenderTargets = new Array();
  17586. // Imported meshes
  17587. this.importedMeshesFiles = new Array();
  17588. // Probes
  17589. this.probesEnabled = true;
  17590. this.reflectionProbes = new Array();
  17591. this._actionManagers = new Array();
  17592. this._meshesForIntersections = new BABYLON.SmartArray(256);
  17593. // Procedural textures
  17594. this.proceduralTexturesEnabled = true;
  17595. this._proceduralTextures = new Array();
  17596. this.soundTracks = new Array();
  17597. this._audioEnabled = true;
  17598. this._headphone = false;
  17599. // Performance counters
  17600. this._totalVertices = new BABYLON.PerfCounter();
  17601. this._activeIndices = new BABYLON.PerfCounter();
  17602. this._activeParticles = new BABYLON.PerfCounter();
  17603. this._activeBones = new BABYLON.PerfCounter();
  17604. this._animationTime = 0;
  17605. this.animationTimeScale = 1;
  17606. this._renderId = 0;
  17607. this._executeWhenReadyTimeoutId = -1;
  17608. this._intermediateRendering = false;
  17609. this._viewUpdateFlag = -1;
  17610. this._projectionUpdateFlag = -1;
  17611. this._alternateViewUpdateFlag = -1;
  17612. this._alternateProjectionUpdateFlag = -1;
  17613. this._toBeDisposed = new BABYLON.SmartArray(256);
  17614. this._pendingData = new Array();
  17615. this._isDisposed = false;
  17616. this._activeMeshes = new BABYLON.SmartArray(256);
  17617. this._processedMaterials = new BABYLON.SmartArray(256);
  17618. this._renderTargets = new BABYLON.SmartArray(256);
  17619. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17620. this._activeSkeletons = new BABYLON.SmartArray(32);
  17621. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17622. this._activeAnimatables = new Array();
  17623. this._transformMatrix = BABYLON.Matrix.Zero();
  17624. this._useAlternateCameraConfiguration = false;
  17625. this._alternateRendering = false;
  17626. this.requireLightSorting = false;
  17627. this._activeMeshesFrozen = false;
  17628. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17629. this._engine.scenes.push(this);
  17630. this._uid = null;
  17631. this._renderingManager = new BABYLON.RenderingManager(this);
  17632. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17633. if (BABYLON.OutlineRenderer) {
  17634. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17635. }
  17636. if (BABYLON.Tools.IsWindowObjectExist()) {
  17637. this.attachControl();
  17638. }
  17639. //simplification queue
  17640. if (BABYLON.SimplificationQueue) {
  17641. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17642. }
  17643. //collision coordinator initialization. For now legacy per default.
  17644. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17645. // Uniform Buffer
  17646. this._createUbo();
  17647. // Default Image processing definition.
  17648. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17649. }
  17650. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17651. /** The fog is deactivated */
  17652. get: function () {
  17653. return Scene._FOGMODE_NONE;
  17654. },
  17655. enumerable: true,
  17656. configurable: true
  17657. });
  17658. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17659. /** The fog density is following an exponential function */
  17660. get: function () {
  17661. return Scene._FOGMODE_EXP;
  17662. },
  17663. enumerable: true,
  17664. configurable: true
  17665. });
  17666. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17667. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17668. get: function () {
  17669. return Scene._FOGMODE_EXP2;
  17670. },
  17671. enumerable: true,
  17672. configurable: true
  17673. });
  17674. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17675. /** The fog density is following a linear function. */
  17676. get: function () {
  17677. return Scene._FOGMODE_LINEAR;
  17678. },
  17679. enumerable: true,
  17680. configurable: true
  17681. });
  17682. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17683. /**
  17684. * Texture used in all pbr material as the reflection texture.
  17685. * As in the majority of the scene they are the same (exception for multi room and so on),
  17686. * this is easier to reference from here than from all the materials.
  17687. */
  17688. get: function () {
  17689. return this._environmentTexture;
  17690. },
  17691. /**
  17692. * Texture used in all pbr material as the reflection texture.
  17693. * As in the majority of the scene they are the same (exception for multi room and so on),
  17694. * this is easier to set here than in all the materials.
  17695. */
  17696. set: function (value) {
  17697. if (this._environmentTexture === value) {
  17698. return;
  17699. }
  17700. this._environmentTexture = value;
  17701. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17702. },
  17703. enumerable: true,
  17704. configurable: true
  17705. });
  17706. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17707. /**
  17708. * Default image processing configuration used either in the rendering
  17709. * Forward main pass or through the imageProcessingPostProcess if present.
  17710. * As in the majority of the scene they are the same (exception for multi camera),
  17711. * this is easier to reference from here than from all the materials and post process.
  17712. *
  17713. * No setter as we it is a shared configuration, you can set the values instead.
  17714. */
  17715. get: function () {
  17716. return this._imageProcessingConfiguration;
  17717. },
  17718. enumerable: true,
  17719. configurable: true
  17720. });
  17721. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17722. get: function () {
  17723. return this._forcePointsCloud;
  17724. },
  17725. set: function (value) {
  17726. if (this._forcePointsCloud === value) {
  17727. return;
  17728. }
  17729. this._forcePointsCloud = value;
  17730. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17731. },
  17732. enumerable: true,
  17733. configurable: true
  17734. });
  17735. Object.defineProperty(Scene.prototype, "onDispose", {
  17736. /** A function to be executed when this scene is disposed. */
  17737. set: function (callback) {
  17738. if (this._onDisposeObserver) {
  17739. this.onDisposeObservable.remove(this._onDisposeObserver);
  17740. }
  17741. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17742. },
  17743. enumerable: true,
  17744. configurable: true
  17745. });
  17746. Object.defineProperty(Scene.prototype, "beforeRender", {
  17747. /** A function to be executed before rendering this scene */
  17748. set: function (callback) {
  17749. if (this._onBeforeRenderObserver) {
  17750. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17751. }
  17752. if (callback) {
  17753. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17754. }
  17755. },
  17756. enumerable: true,
  17757. configurable: true
  17758. });
  17759. Object.defineProperty(Scene.prototype, "afterRender", {
  17760. /** A function to be executed after rendering this scene */
  17761. set: function (callback) {
  17762. if (this._onAfterRenderObserver) {
  17763. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17764. }
  17765. if (callback) {
  17766. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17767. }
  17768. },
  17769. enumerable: true,
  17770. configurable: true
  17771. });
  17772. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17773. set: function (callback) {
  17774. if (this._onBeforeCameraRenderObserver) {
  17775. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17776. }
  17777. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17778. },
  17779. enumerable: true,
  17780. configurable: true
  17781. });
  17782. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17783. set: function (callback) {
  17784. if (this._onAfterCameraRenderObserver) {
  17785. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17786. }
  17787. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17788. },
  17789. enumerable: true,
  17790. configurable: true
  17791. });
  17792. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17793. get: function () {
  17794. if (!this._gamepadManager) {
  17795. this._gamepadManager = new BABYLON.GamepadManager();
  17796. }
  17797. return this._gamepadManager;
  17798. },
  17799. enumerable: true,
  17800. configurable: true
  17801. });
  17802. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17803. get: function () {
  17804. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17810. get: function () {
  17811. return this._useRightHandedSystem;
  17812. },
  17813. set: function (value) {
  17814. if (this._useRightHandedSystem === value) {
  17815. return;
  17816. }
  17817. this._useRightHandedSystem = value;
  17818. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17819. },
  17820. enumerable: true,
  17821. configurable: true
  17822. });
  17823. Scene.prototype.setStepId = function (newStepId) {
  17824. this._currentStepId = newStepId;
  17825. };
  17826. ;
  17827. Scene.prototype.getStepId = function () {
  17828. return this._currentStepId;
  17829. };
  17830. ;
  17831. Scene.prototype.getInternalStep = function () {
  17832. return this._currentInternalStep;
  17833. };
  17834. ;
  17835. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17836. get: function () {
  17837. return this._fogEnabled;
  17838. },
  17839. /**
  17840. * is fog enabled on this scene.
  17841. */
  17842. set: function (value) {
  17843. if (this._fogEnabled === value) {
  17844. return;
  17845. }
  17846. this._fogEnabled = value;
  17847. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17848. },
  17849. enumerable: true,
  17850. configurable: true
  17851. });
  17852. Object.defineProperty(Scene.prototype, "fogMode", {
  17853. get: function () {
  17854. return this._fogMode;
  17855. },
  17856. set: function (value) {
  17857. if (this._fogMode === value) {
  17858. return;
  17859. }
  17860. this._fogMode = value;
  17861. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17862. },
  17863. enumerable: true,
  17864. configurable: true
  17865. });
  17866. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17867. get: function () {
  17868. return this._shadowsEnabled;
  17869. },
  17870. set: function (value) {
  17871. if (this._shadowsEnabled === value) {
  17872. return;
  17873. }
  17874. this._shadowsEnabled = value;
  17875. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17881. get: function () {
  17882. return this._lightsEnabled;
  17883. },
  17884. set: function (value) {
  17885. if (this._lightsEnabled === value) {
  17886. return;
  17887. }
  17888. this._lightsEnabled = value;
  17889. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17890. },
  17891. enumerable: true,
  17892. configurable: true
  17893. });
  17894. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17895. /** The default material used on meshes when no material is affected */
  17896. get: function () {
  17897. if (!this._defaultMaterial) {
  17898. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17899. }
  17900. return this._defaultMaterial;
  17901. },
  17902. /** The default material used on meshes when no material is affected */
  17903. set: function (value) {
  17904. this._defaultMaterial = value;
  17905. },
  17906. enumerable: true,
  17907. configurable: true
  17908. });
  17909. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17910. get: function () {
  17911. return this._texturesEnabled;
  17912. },
  17913. set: function (value) {
  17914. if (this._texturesEnabled === value) {
  17915. return;
  17916. }
  17917. this._texturesEnabled = value;
  17918. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17919. },
  17920. enumerable: true,
  17921. configurable: true
  17922. });
  17923. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17924. get: function () {
  17925. return this._skeletonsEnabled;
  17926. },
  17927. set: function (value) {
  17928. if (this._skeletonsEnabled === value) {
  17929. return;
  17930. }
  17931. this._skeletonsEnabled = value;
  17932. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17933. },
  17934. enumerable: true,
  17935. configurable: true
  17936. });
  17937. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17938. get: function () {
  17939. if (!this._postProcessRenderPipelineManager) {
  17940. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17941. }
  17942. return this._postProcessRenderPipelineManager;
  17943. },
  17944. enumerable: true,
  17945. configurable: true
  17946. });
  17947. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17948. get: function () {
  17949. if (!this._mainSoundTrack) {
  17950. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17951. }
  17952. return this._mainSoundTrack;
  17953. },
  17954. enumerable: true,
  17955. configurable: true
  17956. });
  17957. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17958. get: function () {
  17959. return this._alternateRendering;
  17960. },
  17961. enumerable: true,
  17962. configurable: true
  17963. });
  17964. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17965. get: function () {
  17966. return this._frustumPlanes;
  17967. },
  17968. enumerable: true,
  17969. configurable: true
  17970. });
  17971. Object.defineProperty(Scene.prototype, "debugLayer", {
  17972. // Properties
  17973. get: function () {
  17974. if (!this._debugLayer) {
  17975. this._debugLayer = new BABYLON.DebugLayer(this);
  17976. }
  17977. return this._debugLayer;
  17978. },
  17979. enumerable: true,
  17980. configurable: true
  17981. });
  17982. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17983. get: function () {
  17984. return this._workerCollisions;
  17985. },
  17986. set: function (enabled) {
  17987. if (!BABYLON.CollisionCoordinatorLegacy) {
  17988. return;
  17989. }
  17990. enabled = (enabled && !!Worker);
  17991. this._workerCollisions = enabled;
  17992. if (this.collisionCoordinator) {
  17993. this.collisionCoordinator.destroy();
  17994. }
  17995. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17996. this.collisionCoordinator.init(this);
  17997. },
  17998. enumerable: true,
  17999. configurable: true
  18000. });
  18001. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18002. get: function () {
  18003. return this._selectionOctree;
  18004. },
  18005. enumerable: true,
  18006. configurable: true
  18007. });
  18008. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18009. /**
  18010. * The mesh that is currently under the pointer.
  18011. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18012. */
  18013. get: function () {
  18014. return this._pointerOverMesh;
  18015. },
  18016. enumerable: true,
  18017. configurable: true
  18018. });
  18019. Object.defineProperty(Scene.prototype, "pointerX", {
  18020. /**
  18021. * Current on-screen X position of the pointer
  18022. * @return {number} X position of the pointer
  18023. */
  18024. get: function () {
  18025. return this._pointerX;
  18026. },
  18027. enumerable: true,
  18028. configurable: true
  18029. });
  18030. Object.defineProperty(Scene.prototype, "pointerY", {
  18031. /**
  18032. * Current on-screen Y position of the pointer
  18033. * @return {number} Y position of the pointer
  18034. */
  18035. get: function () {
  18036. return this._pointerY;
  18037. },
  18038. enumerable: true,
  18039. configurable: true
  18040. });
  18041. Scene.prototype.getCachedMaterial = function () {
  18042. return this._cachedMaterial;
  18043. };
  18044. Scene.prototype.getCachedEffect = function () {
  18045. return this._cachedEffect;
  18046. };
  18047. Scene.prototype.getCachedVisibility = function () {
  18048. return this._cachedVisibility;
  18049. };
  18050. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18051. if (visibility === void 0) { visibility = 1; }
  18052. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18053. };
  18054. Scene.prototype.getBoundingBoxRenderer = function () {
  18055. if (!this._boundingBoxRenderer) {
  18056. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18057. }
  18058. return this._boundingBoxRenderer;
  18059. };
  18060. Scene.prototype.getOutlineRenderer = function () {
  18061. return this._outlineRenderer;
  18062. };
  18063. Scene.prototype.getEngine = function () {
  18064. return this._engine;
  18065. };
  18066. Scene.prototype.getTotalVertices = function () {
  18067. return this._totalVertices.current;
  18068. };
  18069. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18070. get: function () {
  18071. return this._totalVertices;
  18072. },
  18073. enumerable: true,
  18074. configurable: true
  18075. });
  18076. Scene.prototype.getActiveIndices = function () {
  18077. return this._activeIndices.current;
  18078. };
  18079. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18080. get: function () {
  18081. return this._activeIndices;
  18082. },
  18083. enumerable: true,
  18084. configurable: true
  18085. });
  18086. Scene.prototype.getActiveParticles = function () {
  18087. return this._activeParticles.current;
  18088. };
  18089. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18090. get: function () {
  18091. return this._activeParticles;
  18092. },
  18093. enumerable: true,
  18094. configurable: true
  18095. });
  18096. Scene.prototype.getActiveBones = function () {
  18097. return this._activeBones.current;
  18098. };
  18099. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18100. get: function () {
  18101. return this._activeBones;
  18102. },
  18103. enumerable: true,
  18104. configurable: true
  18105. });
  18106. // Stats
  18107. Scene.prototype.getInterFramePerfCounter = function () {
  18108. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18109. return 0;
  18110. };
  18111. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18112. get: function () {
  18113. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18114. return null;
  18115. },
  18116. enumerable: true,
  18117. configurable: true
  18118. });
  18119. Scene.prototype.getLastFrameDuration = function () {
  18120. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18121. return 0;
  18122. };
  18123. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18124. get: function () {
  18125. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18126. return null;
  18127. },
  18128. enumerable: true,
  18129. configurable: true
  18130. });
  18131. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18132. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18133. return 0;
  18134. };
  18135. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18136. get: function () {
  18137. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18138. return null;
  18139. },
  18140. enumerable: true,
  18141. configurable: true
  18142. });
  18143. Scene.prototype.getActiveMeshes = function () {
  18144. return this._activeMeshes;
  18145. };
  18146. Scene.prototype.getRenderTargetsDuration = function () {
  18147. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18148. return 0;
  18149. };
  18150. Scene.prototype.getRenderDuration = function () {
  18151. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18152. return 0;
  18153. };
  18154. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18155. get: function () {
  18156. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18157. return null;
  18158. },
  18159. enumerable: true,
  18160. configurable: true
  18161. });
  18162. Scene.prototype.getParticlesDuration = function () {
  18163. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18164. return 0;
  18165. };
  18166. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18167. get: function () {
  18168. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18169. return null;
  18170. },
  18171. enumerable: true,
  18172. configurable: true
  18173. });
  18174. Scene.prototype.getSpritesDuration = function () {
  18175. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18176. return 0;
  18177. };
  18178. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18179. get: function () {
  18180. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18181. return null;
  18182. },
  18183. enumerable: true,
  18184. configurable: true
  18185. });
  18186. Scene.prototype.getAnimationRatio = function () {
  18187. return this._animationRatio;
  18188. };
  18189. Scene.prototype.getRenderId = function () {
  18190. return this._renderId;
  18191. };
  18192. Scene.prototype.incrementRenderId = function () {
  18193. this._renderId++;
  18194. };
  18195. Scene.prototype._updatePointerPosition = function (evt) {
  18196. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18197. if (!canvasRect) {
  18198. return;
  18199. }
  18200. this._pointerX = evt.clientX - canvasRect.left;
  18201. this._pointerY = evt.clientY - canvasRect.top;
  18202. this._unTranslatedPointerX = this._pointerX;
  18203. this._unTranslatedPointerY = this._pointerY;
  18204. };
  18205. Scene.prototype._createUbo = function () {
  18206. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18207. this._sceneUbo.addUniform("viewProjection", 16);
  18208. this._sceneUbo.addUniform("view", 16);
  18209. };
  18210. Scene.prototype._createAlternateUbo = function () {
  18211. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18212. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18213. this._alternateSceneUbo.addUniform("view", 16);
  18214. };
  18215. // Pointers handling
  18216. /**
  18217. * Use this method to simulate a pointer move on a mesh
  18218. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18219. */
  18220. Scene.prototype.simulatePointerMove = function (pickResult) {
  18221. var evt = new PointerEvent("pointermove");
  18222. return this._processPointerMove(pickResult, evt);
  18223. };
  18224. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18225. var canvas = this._engine.getRenderingCanvas();
  18226. if (!canvas) {
  18227. return this;
  18228. }
  18229. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18230. this.setPointerOverSprite(null);
  18231. this.setPointerOverMesh(pickResult.pickedMesh);
  18232. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18233. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18234. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18235. }
  18236. else {
  18237. canvas.style.cursor = this.hoverCursor;
  18238. }
  18239. }
  18240. else {
  18241. canvas.style.cursor = this.defaultCursor;
  18242. }
  18243. }
  18244. else {
  18245. this.setPointerOverMesh(null);
  18246. // Sprites
  18247. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18248. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18249. this.setPointerOverSprite(pickResult.pickedSprite);
  18250. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18251. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18252. }
  18253. else {
  18254. canvas.style.cursor = this.hoverCursor;
  18255. }
  18256. }
  18257. else {
  18258. this.setPointerOverSprite(null);
  18259. // Restore pointer
  18260. canvas.style.cursor = this.defaultCursor;
  18261. }
  18262. }
  18263. if (pickResult) {
  18264. if (this.onPointerMove) {
  18265. this.onPointerMove(evt, pickResult);
  18266. }
  18267. if (this.onPointerObservable.hasObservers()) {
  18268. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18269. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18270. this.onPointerObservable.notifyObservers(pi, type);
  18271. }
  18272. }
  18273. return this;
  18274. };
  18275. /**
  18276. * Use this method to simulate a pointer down on a mesh
  18277. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18278. */
  18279. Scene.prototype.simulatePointerDown = function (pickResult) {
  18280. var evt = new PointerEvent("pointerdown");
  18281. return this._processPointerDown(pickResult, evt);
  18282. };
  18283. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18284. var _this = this;
  18285. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18286. this._pickedDownMesh = pickResult.pickedMesh;
  18287. var actionManager = pickResult.pickedMesh.actionManager;
  18288. if (actionManager) {
  18289. if (actionManager.hasPickTriggers) {
  18290. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18291. switch (evt.button) {
  18292. case 0:
  18293. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18294. break;
  18295. case 1:
  18296. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18297. break;
  18298. case 2:
  18299. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18300. break;
  18301. }
  18302. }
  18303. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18304. window.setTimeout(function () {
  18305. 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);
  18306. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18307. if (_this._totalPointersPressed !== 0 &&
  18308. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18309. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18310. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18311. _this._startingPointerTime = 0;
  18312. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18313. }
  18314. }
  18315. }, Scene.LongPressDelay);
  18316. }
  18317. }
  18318. }
  18319. if (pickResult) {
  18320. if (this.onPointerDown) {
  18321. this.onPointerDown(evt, pickResult);
  18322. }
  18323. if (this.onPointerObservable.hasObservers()) {
  18324. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18325. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18326. this.onPointerObservable.notifyObservers(pi, type);
  18327. }
  18328. }
  18329. return this;
  18330. };
  18331. /**
  18332. * Use this method to simulate a pointer up on a mesh
  18333. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18334. */
  18335. Scene.prototype.simulatePointerUp = function (pickResult) {
  18336. var evt = new PointerEvent("pointerup");
  18337. var clickInfo = new ClickInfo();
  18338. clickInfo.singleClick = true;
  18339. return this._processPointerUp(pickResult, evt, clickInfo);
  18340. };
  18341. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18342. if (pickResult && pickResult && pickResult.pickedMesh) {
  18343. this._pickedUpMesh = pickResult.pickedMesh;
  18344. if (this._pickedDownMesh === this._pickedUpMesh) {
  18345. if (this.onPointerPick) {
  18346. this.onPointerPick(evt, pickResult);
  18347. }
  18348. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18349. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18350. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18351. this.onPointerObservable.notifyObservers(pi, type);
  18352. }
  18353. }
  18354. if (pickResult.pickedMesh.actionManager) {
  18355. if (clickInfo.ignore) {
  18356. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18357. }
  18358. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18359. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18360. }
  18361. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18362. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18363. }
  18364. }
  18365. }
  18366. if (this._pickedDownMesh &&
  18367. this._pickedDownMesh.actionManager &&
  18368. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18369. this._pickedDownMesh !== this._pickedUpMesh) {
  18370. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18371. }
  18372. if (this.onPointerUp) {
  18373. this.onPointerUp(evt, pickResult);
  18374. }
  18375. if (this.onPointerObservable.hasObservers()) {
  18376. if (!clickInfo.ignore) {
  18377. if (!clickInfo.hasSwiped) {
  18378. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18379. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18380. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18381. this.onPointerObservable.notifyObservers(pi, type);
  18382. }
  18383. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18384. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18385. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18386. this.onPointerObservable.notifyObservers(pi, type);
  18387. }
  18388. }
  18389. }
  18390. else {
  18391. var type = BABYLON.PointerEventTypes.POINTERUP;
  18392. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18393. this.onPointerObservable.notifyObservers(pi, type);
  18394. }
  18395. }
  18396. return this;
  18397. };
  18398. /**
  18399. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18400. * @param attachUp defines if you want to attach events to pointerup
  18401. * @param attachDown defines if you want to attach events to pointerdown
  18402. * @param attachMove defines if you want to attach events to pointermove
  18403. */
  18404. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18405. var _this = this;
  18406. if (attachUp === void 0) { attachUp = true; }
  18407. if (attachDown === void 0) { attachDown = true; }
  18408. if (attachMove === void 0) { attachMove = true; }
  18409. this._initActionManager = function (act, clickInfo) {
  18410. if (!_this._meshPickProceed) {
  18411. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18412. _this._currentPickResult = pickResult;
  18413. if (pickResult) {
  18414. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18415. }
  18416. _this._meshPickProceed = true;
  18417. }
  18418. return act;
  18419. };
  18420. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18421. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18422. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18423. btn !== _this._previousButtonPressed) {
  18424. _this._doubleClickOccured = false;
  18425. clickInfo.singleClick = true;
  18426. clickInfo.ignore = false;
  18427. cb(clickInfo, _this._currentPickResult);
  18428. }
  18429. };
  18430. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18431. var clickInfo = new ClickInfo();
  18432. _this._currentPickResult = null;
  18433. var act = null;
  18434. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18435. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18436. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18437. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18438. act = _this._initActionManager(act, clickInfo);
  18439. if (act)
  18440. checkPicking = act.hasPickTriggers;
  18441. }
  18442. if (checkPicking) {
  18443. var btn = evt.button;
  18444. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18445. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18446. if (!clickInfo.hasSwiped) {
  18447. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18448. if (!checkSingleClickImmediately) {
  18449. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18450. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18451. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18452. act = _this._initActionManager(act, clickInfo);
  18453. if (act)
  18454. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18455. }
  18456. }
  18457. if (checkSingleClickImmediately) {
  18458. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18459. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18460. btn !== _this._previousButtonPressed) {
  18461. clickInfo.singleClick = true;
  18462. cb(clickInfo, _this._currentPickResult);
  18463. }
  18464. }
  18465. else {
  18466. // wait that no double click has been raised during the double click delay
  18467. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18468. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18469. }
  18470. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18471. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18472. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18473. act = _this._initActionManager(act, clickInfo);
  18474. if (act)
  18475. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18476. }
  18477. if (checkDoubleClick) {
  18478. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18479. if (btn === _this._previousButtonPressed &&
  18480. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18481. !_this._doubleClickOccured) {
  18482. // pointer has not moved for 2 clicks, it's a double click
  18483. if (!clickInfo.hasSwiped &&
  18484. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18485. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18486. _this._previousStartingPointerTime = 0;
  18487. _this._doubleClickOccured = true;
  18488. clickInfo.doubleClick = true;
  18489. clickInfo.ignore = false;
  18490. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18491. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18492. }
  18493. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18494. cb(clickInfo, _this._currentPickResult);
  18495. }
  18496. else {
  18497. _this._doubleClickOccured = false;
  18498. _this._previousStartingPointerTime = _this._startingPointerTime;
  18499. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18500. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18501. _this._previousButtonPressed = btn;
  18502. _this._previousHasSwiped = clickInfo.hasSwiped;
  18503. if (Scene.ExclusiveDoubleClickMode) {
  18504. if (_this._previousDelayedSimpleClickTimeout) {
  18505. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18506. }
  18507. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18508. cb(clickInfo, _this._previousPickResult);
  18509. }
  18510. else {
  18511. cb(clickInfo, _this._currentPickResult);
  18512. }
  18513. }
  18514. }
  18515. else {
  18516. _this._doubleClickOccured = false;
  18517. _this._previousStartingPointerTime = _this._startingPointerTime;
  18518. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18519. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18520. _this._previousButtonPressed = btn;
  18521. _this._previousHasSwiped = clickInfo.hasSwiped;
  18522. }
  18523. }
  18524. }
  18525. }
  18526. clickInfo.ignore = true;
  18527. cb(clickInfo, _this._currentPickResult);
  18528. };
  18529. this._spritePredicate = function (sprite) {
  18530. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18531. };
  18532. this._onPointerMove = function (evt) {
  18533. _this._updatePointerPosition(evt);
  18534. // PreObservable support
  18535. if (_this.onPrePointerObservable.hasObservers()) {
  18536. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18537. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18538. _this.onPrePointerObservable.notifyObservers(pi, type);
  18539. if (pi.skipOnPointerObservable) {
  18540. return;
  18541. }
  18542. }
  18543. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18544. return;
  18545. }
  18546. if (!_this.pointerMovePredicate) {
  18547. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18548. }
  18549. // Meshes
  18550. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18551. _this._processPointerMove(pickResult, evt);
  18552. };
  18553. this._onPointerDown = function (evt) {
  18554. _this._totalPointersPressed++;
  18555. _this._pickedDownMesh = null;
  18556. _this._meshPickProceed = false;
  18557. _this._updatePointerPosition(evt);
  18558. if (_this.preventDefaultOnPointerDown && canvas) {
  18559. evt.preventDefault();
  18560. canvas.focus();
  18561. }
  18562. // PreObservable support
  18563. if (_this.onPrePointerObservable.hasObservers()) {
  18564. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18565. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18566. _this.onPrePointerObservable.notifyObservers(pi, type);
  18567. if (pi.skipOnPointerObservable) {
  18568. return;
  18569. }
  18570. }
  18571. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18572. return;
  18573. }
  18574. _this._startingPointerPosition.x = _this._pointerX;
  18575. _this._startingPointerPosition.y = _this._pointerY;
  18576. _this._startingPointerTime = new Date().getTime();
  18577. if (!_this.pointerDownPredicate) {
  18578. _this.pointerDownPredicate = function (mesh) {
  18579. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18580. };
  18581. }
  18582. // Meshes
  18583. _this._pickedDownMesh = null;
  18584. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18585. _this._processPointerDown(pickResult, evt);
  18586. // Sprites
  18587. _this._pickedDownSprite = null;
  18588. if (_this.spriteManagers.length > 0) {
  18589. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18590. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18591. if (pickResult.pickedSprite.actionManager) {
  18592. _this._pickedDownSprite = pickResult.pickedSprite;
  18593. switch (evt.button) {
  18594. case 0:
  18595. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18596. break;
  18597. case 1:
  18598. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18599. break;
  18600. case 2:
  18601. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18602. break;
  18603. }
  18604. if (pickResult.pickedSprite.actionManager) {
  18605. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18606. }
  18607. }
  18608. }
  18609. }
  18610. };
  18611. this._onPointerUp = function (evt) {
  18612. if (_this._totalPointersPressed === 0) {
  18613. return; // So we need to test it the pointer down was pressed before.
  18614. }
  18615. _this._totalPointersPressed--;
  18616. _this._pickedUpMesh = null;
  18617. _this._meshPickProceed = false;
  18618. _this._updatePointerPosition(evt);
  18619. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  18620. // PreObservable support
  18621. if (_this.onPrePointerObservable.hasObservers()) {
  18622. if (!clickInfo.ignore) {
  18623. if (!clickInfo.hasSwiped) {
  18624. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18625. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18626. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18627. _this.onPrePointerObservable.notifyObservers(pi, type);
  18628. if (pi.skipOnPointerObservable) {
  18629. return;
  18630. }
  18631. }
  18632. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18633. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18634. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18635. _this.onPrePointerObservable.notifyObservers(pi, type);
  18636. if (pi.skipOnPointerObservable) {
  18637. return;
  18638. }
  18639. }
  18640. }
  18641. }
  18642. else {
  18643. var type = BABYLON.PointerEventTypes.POINTERUP;
  18644. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18645. _this.onPrePointerObservable.notifyObservers(pi, type);
  18646. if (pi.skipOnPointerObservable) {
  18647. return;
  18648. }
  18649. }
  18650. }
  18651. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18652. return;
  18653. }
  18654. if (!_this.pointerUpPredicate) {
  18655. _this.pointerUpPredicate = function (mesh) {
  18656. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18657. };
  18658. }
  18659. // Meshes
  18660. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18661. _this._initActionManager(null, clickInfo);
  18662. }
  18663. if (!pickResult) {
  18664. pickResult = _this._currentPickResult;
  18665. }
  18666. _this._processPointerUp(pickResult, evt, clickInfo);
  18667. // Sprites
  18668. if (_this.spriteManagers.length > 0) {
  18669. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18670. if (spritePickResult) {
  18671. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  18672. if (spritePickResult.pickedSprite.actionManager) {
  18673. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18674. if (spritePickResult.pickedSprite.actionManager) {
  18675. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18676. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18677. }
  18678. }
  18679. }
  18680. }
  18681. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  18682. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18683. }
  18684. }
  18685. }
  18686. _this._previousPickResult = _this._currentPickResult;
  18687. });
  18688. };
  18689. this._onKeyDown = function (evt) {
  18690. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18691. if (_this.onPreKeyboardObservable.hasObservers()) {
  18692. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18693. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18694. if (pi.skipOnPointerObservable) {
  18695. return;
  18696. }
  18697. }
  18698. if (_this.onKeyboardObservable.hasObservers()) {
  18699. var pi = new BABYLON.KeyboardInfo(type, evt);
  18700. _this.onKeyboardObservable.notifyObservers(pi, type);
  18701. }
  18702. if (_this.actionManager) {
  18703. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18704. }
  18705. };
  18706. this._onKeyUp = function (evt) {
  18707. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18708. if (_this.onPreKeyboardObservable.hasObservers()) {
  18709. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18710. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18711. if (pi.skipOnPointerObservable) {
  18712. return;
  18713. }
  18714. }
  18715. if (_this.onKeyboardObservable.hasObservers()) {
  18716. var pi = new BABYLON.KeyboardInfo(type, evt);
  18717. _this.onKeyboardObservable.notifyObservers(pi, type);
  18718. }
  18719. if (_this.actionManager) {
  18720. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18721. }
  18722. };
  18723. var engine = this.getEngine();
  18724. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18725. if (!canvas) {
  18726. return;
  18727. }
  18728. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18729. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18730. });
  18731. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18732. if (!canvas) {
  18733. return;
  18734. }
  18735. canvas.removeEventListener("keydown", _this._onKeyDown);
  18736. canvas.removeEventListener("keyup", _this._onKeyUp);
  18737. });
  18738. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18739. var canvas = this._engine.getRenderingCanvas();
  18740. if (!canvas) {
  18741. return;
  18742. }
  18743. if (attachMove) {
  18744. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18745. // Wheel
  18746. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18747. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18748. }
  18749. if (attachDown) {
  18750. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18751. }
  18752. if (attachUp) {
  18753. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18754. }
  18755. canvas.tabIndex = 1;
  18756. };
  18757. Scene.prototype.detachControl = function () {
  18758. var engine = this.getEngine();
  18759. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18760. var canvas = engine.getRenderingCanvas();
  18761. if (!canvas) {
  18762. return;
  18763. }
  18764. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18765. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18766. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18767. if (this._onCanvasBlurObserver) {
  18768. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18769. }
  18770. if (this._onCanvasFocusObserver) {
  18771. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18772. }
  18773. // Wheel
  18774. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18775. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18776. // Keyboard
  18777. canvas.removeEventListener("keydown", this._onKeyDown);
  18778. canvas.removeEventListener("keyup", this._onKeyUp);
  18779. // Observables
  18780. this.onKeyboardObservable.clear();
  18781. this.onPreKeyboardObservable.clear();
  18782. this.onPointerObservable.clear();
  18783. this.onPrePointerObservable.clear();
  18784. };
  18785. // Ready
  18786. Scene.prototype.isReady = function () {
  18787. if (this._isDisposed) {
  18788. return false;
  18789. }
  18790. if (this._pendingData.length > 0) {
  18791. return false;
  18792. }
  18793. var index;
  18794. // Geometries
  18795. for (index = 0; index < this._geometries.length; index++) {
  18796. var geometry = this._geometries[index];
  18797. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18798. return false;
  18799. }
  18800. }
  18801. // Meshes
  18802. for (index = 0; index < this.meshes.length; index++) {
  18803. var mesh = this.meshes[index];
  18804. if (!mesh.isEnabled()) {
  18805. continue;
  18806. }
  18807. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18808. continue;
  18809. }
  18810. if (!mesh.isReady()) {
  18811. return false;
  18812. }
  18813. var mat = mesh.material;
  18814. if (mat) {
  18815. if (!mat.isReady(mesh)) {
  18816. return false;
  18817. }
  18818. }
  18819. }
  18820. return true;
  18821. };
  18822. Scene.prototype.resetCachedMaterial = function () {
  18823. this._cachedMaterial = null;
  18824. this._cachedEffect = null;
  18825. this._cachedVisibility = null;
  18826. };
  18827. Scene.prototype.registerBeforeRender = function (func) {
  18828. this.onBeforeRenderObservable.add(func);
  18829. };
  18830. Scene.prototype.unregisterBeforeRender = function (func) {
  18831. this.onBeforeRenderObservable.removeCallback(func);
  18832. };
  18833. Scene.prototype.registerAfterRender = function (func) {
  18834. this.onAfterRenderObservable.add(func);
  18835. };
  18836. Scene.prototype.unregisterAfterRender = function (func) {
  18837. this.onAfterRenderObservable.removeCallback(func);
  18838. };
  18839. Scene.prototype._addPendingData = function (data) {
  18840. this._pendingData.push(data);
  18841. };
  18842. Scene.prototype._removePendingData = function (data) {
  18843. var index = this._pendingData.indexOf(data);
  18844. if (index !== -1) {
  18845. this._pendingData.splice(index, 1);
  18846. }
  18847. };
  18848. Scene.prototype.getWaitingItemsCount = function () {
  18849. return this._pendingData.length;
  18850. };
  18851. /**
  18852. * Registers a function to be executed when the scene is ready.
  18853. * @param {Function} func - the function to be executed.
  18854. */
  18855. Scene.prototype.executeWhenReady = function (func) {
  18856. var _this = this;
  18857. this.onReadyObservable.add(func);
  18858. if (this._executeWhenReadyTimeoutId !== -1) {
  18859. return;
  18860. }
  18861. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18862. _this._checkIsReady();
  18863. }, 150);
  18864. };
  18865. Scene.prototype._checkIsReady = function () {
  18866. var _this = this;
  18867. if (this.isReady()) {
  18868. this.onReadyObservable.notifyObservers(this);
  18869. this.onReadyObservable.clear();
  18870. this._executeWhenReadyTimeoutId = -1;
  18871. return;
  18872. }
  18873. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18874. _this._checkIsReady();
  18875. }, 150);
  18876. };
  18877. // Animations
  18878. /**
  18879. * Will start the animation sequence of a given target
  18880. * @param target - the target
  18881. * @param {number} from - from which frame should animation start
  18882. * @param {number} to - till which frame should animation run.
  18883. * @param {boolean} [loop] - should the animation loop
  18884. * @param {number} [speedRatio] - the speed in which to run the animation
  18885. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18886. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18887. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18888. * See BABYLON.Animatable
  18889. */
  18890. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18891. if (speedRatio === void 0) { speedRatio = 1.0; }
  18892. if (from > to && speedRatio > 0) {
  18893. speedRatio *= -1;
  18894. }
  18895. this.stopAnimation(target);
  18896. if (!animatable) {
  18897. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18898. }
  18899. // Local animations
  18900. if (target.animations) {
  18901. animatable.appendAnimations(target, target.animations);
  18902. }
  18903. // Children animations
  18904. if (target.getAnimatables) {
  18905. var animatables = target.getAnimatables();
  18906. for (var index = 0; index < animatables.length; index++) {
  18907. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18908. }
  18909. }
  18910. animatable.reset();
  18911. return animatable;
  18912. };
  18913. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18914. if (speedRatio === undefined) {
  18915. speedRatio = 1.0;
  18916. }
  18917. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18918. return animatable;
  18919. };
  18920. Scene.prototype.getAnimatableByTarget = function (target) {
  18921. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18922. if (this._activeAnimatables[index].target === target) {
  18923. return this._activeAnimatables[index];
  18924. }
  18925. }
  18926. return null;
  18927. };
  18928. Object.defineProperty(Scene.prototype, "Animatables", {
  18929. get: function () {
  18930. return this._activeAnimatables;
  18931. },
  18932. enumerable: true,
  18933. configurable: true
  18934. });
  18935. /**
  18936. * Will stop the animation of the given target
  18937. * @param target - the target
  18938. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18939. * @see beginAnimation
  18940. */
  18941. Scene.prototype.stopAnimation = function (target, animationName) {
  18942. var animatable = this.getAnimatableByTarget(target);
  18943. if (animatable) {
  18944. animatable.stop(animationName);
  18945. }
  18946. };
  18947. Scene.prototype._animate = function () {
  18948. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18949. return;
  18950. }
  18951. // Getting time
  18952. var now = BABYLON.Tools.Now;
  18953. if (!this._animationTimeLast) {
  18954. if (this._pendingData.length > 0) {
  18955. return;
  18956. }
  18957. this._animationTimeLast = now;
  18958. }
  18959. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18960. this._animationTime += deltaTime;
  18961. this._animationTimeLast = now;
  18962. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18963. this._activeAnimatables[index]._animate(this._animationTime);
  18964. }
  18965. };
  18966. // Matrix
  18967. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18968. this._useAlternateCameraConfiguration = active;
  18969. };
  18970. Scene.prototype.getViewMatrix = function () {
  18971. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18972. };
  18973. Scene.prototype.getProjectionMatrix = function () {
  18974. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18975. };
  18976. Scene.prototype.getTransformMatrix = function () {
  18977. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18978. };
  18979. Scene.prototype.setTransformMatrix = function (view, projection) {
  18980. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18981. return;
  18982. }
  18983. this._viewUpdateFlag = view.updateFlag;
  18984. this._projectionUpdateFlag = projection.updateFlag;
  18985. this._viewMatrix = view;
  18986. this._projectionMatrix = projection;
  18987. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18988. // Update frustum
  18989. if (!this._frustumPlanes) {
  18990. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18991. }
  18992. else {
  18993. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18994. }
  18995. if (this.activeCamera && this.activeCamera._alternateCamera) {
  18996. var otherCamera = this.activeCamera._alternateCamera;
  18997. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  18998. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  18999. }
  19000. if (this._sceneUbo.useUbo) {
  19001. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19002. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19003. this._sceneUbo.update();
  19004. }
  19005. };
  19006. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19007. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19008. return;
  19009. }
  19010. this._alternateViewUpdateFlag = view.updateFlag;
  19011. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19012. this._alternateViewMatrix = view;
  19013. this._alternateProjectionMatrix = projection;
  19014. if (!this._alternateTransformMatrix) {
  19015. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19016. }
  19017. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19018. if (!this._alternateSceneUbo) {
  19019. this._createAlternateUbo();
  19020. }
  19021. if (this._alternateSceneUbo.useUbo) {
  19022. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19023. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19024. this._alternateSceneUbo.update();
  19025. }
  19026. };
  19027. Scene.prototype.getSceneUniformBuffer = function () {
  19028. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19029. };
  19030. // Methods
  19031. Scene.prototype.getUniqueId = function () {
  19032. var result = Scene._uniqueIdCounter;
  19033. Scene._uniqueIdCounter++;
  19034. return result;
  19035. };
  19036. Scene.prototype.addMesh = function (newMesh) {
  19037. this.meshes.push(newMesh);
  19038. //notify the collision coordinator
  19039. if (this.collisionCoordinator) {
  19040. this.collisionCoordinator.onMeshAdded(newMesh);
  19041. }
  19042. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19043. };
  19044. Scene.prototype.removeMesh = function (toRemove) {
  19045. var index = this.meshes.indexOf(toRemove);
  19046. if (index !== -1) {
  19047. // Remove from the scene if mesh found
  19048. this.meshes.splice(index, 1);
  19049. }
  19050. //notify the collision coordinator
  19051. if (this.collisionCoordinator) {
  19052. this.collisionCoordinator.onMeshRemoved(toRemove);
  19053. }
  19054. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19055. return index;
  19056. };
  19057. Scene.prototype.removeSkeleton = function (toRemove) {
  19058. var index = this.skeletons.indexOf(toRemove);
  19059. if (index !== -1) {
  19060. // Remove from the scene if found
  19061. this.skeletons.splice(index, 1);
  19062. }
  19063. return index;
  19064. };
  19065. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19066. var index = this.morphTargetManagers.indexOf(toRemove);
  19067. if (index !== -1) {
  19068. // Remove from the scene if found
  19069. this.morphTargetManagers.splice(index, 1);
  19070. }
  19071. return index;
  19072. };
  19073. Scene.prototype.removeLight = function (toRemove) {
  19074. var index = this.lights.indexOf(toRemove);
  19075. if (index !== -1) {
  19076. // Remove from the scene if mesh found
  19077. this.lights.splice(index, 1);
  19078. this.sortLightsByPriority();
  19079. }
  19080. this.onLightRemovedObservable.notifyObservers(toRemove);
  19081. return index;
  19082. };
  19083. Scene.prototype.removeCamera = function (toRemove) {
  19084. var index = this.cameras.indexOf(toRemove);
  19085. if (index !== -1) {
  19086. // Remove from the scene if mesh found
  19087. this.cameras.splice(index, 1);
  19088. }
  19089. // Remove from activeCameras
  19090. var index2 = this.activeCameras.indexOf(toRemove);
  19091. if (index2 !== -1) {
  19092. // Remove from the scene if mesh found
  19093. this.activeCameras.splice(index2, 1);
  19094. }
  19095. // Reset the activeCamera
  19096. if (this.activeCamera === toRemove) {
  19097. if (this.cameras.length > 0) {
  19098. this.activeCamera = this.cameras[0];
  19099. }
  19100. else {
  19101. this.activeCamera = null;
  19102. }
  19103. }
  19104. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19105. return index;
  19106. };
  19107. Scene.prototype.addLight = function (newLight) {
  19108. this.lights.push(newLight);
  19109. this.sortLightsByPriority();
  19110. this.onNewLightAddedObservable.notifyObservers(newLight);
  19111. };
  19112. Scene.prototype.sortLightsByPriority = function () {
  19113. if (this.requireLightSorting) {
  19114. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19115. }
  19116. };
  19117. Scene.prototype.addCamera = function (newCamera) {
  19118. this.cameras.push(newCamera);
  19119. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19120. };
  19121. /**
  19122. * Switch active camera
  19123. * @param {Camera} newCamera - new active camera
  19124. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19125. */
  19126. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19127. if (attachControl === void 0) { attachControl = true; }
  19128. var canvas = this._engine.getRenderingCanvas();
  19129. if (!canvas) {
  19130. return;
  19131. }
  19132. if (this.activeCamera) {
  19133. this.activeCamera.detachControl(canvas);
  19134. }
  19135. this.activeCamera = newCamera;
  19136. if (attachControl) {
  19137. newCamera.attachControl(canvas);
  19138. }
  19139. };
  19140. /**
  19141. * sets the active camera of the scene using its ID
  19142. * @param {string} id - the camera's ID
  19143. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19144. * @see activeCamera
  19145. */
  19146. Scene.prototype.setActiveCameraByID = function (id) {
  19147. var camera = this.getCameraByID(id);
  19148. if (camera) {
  19149. this.activeCamera = camera;
  19150. return camera;
  19151. }
  19152. return null;
  19153. };
  19154. /**
  19155. * sets the active camera of the scene using its name
  19156. * @param {string} name - the camera's name
  19157. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19158. * @see activeCamera
  19159. */
  19160. Scene.prototype.setActiveCameraByName = function (name) {
  19161. var camera = this.getCameraByName(name);
  19162. if (camera) {
  19163. this.activeCamera = camera;
  19164. return camera;
  19165. }
  19166. return null;
  19167. };
  19168. /**
  19169. * get a material using its id
  19170. * @param {string} the material's ID
  19171. * @return {BABYLON.Material|null} the material or null if none found.
  19172. */
  19173. Scene.prototype.getMaterialByID = function (id) {
  19174. for (var index = 0; index < this.materials.length; index++) {
  19175. if (this.materials[index].id === id) {
  19176. return this.materials[index];
  19177. }
  19178. }
  19179. return null;
  19180. };
  19181. /**
  19182. * get a material using its name
  19183. * @param {string} the material's name
  19184. * @return {BABYLON.Material|null} the material or null if none found.
  19185. */
  19186. Scene.prototype.getMaterialByName = function (name) {
  19187. for (var index = 0; index < this.materials.length; index++) {
  19188. if (this.materials[index].name === name) {
  19189. return this.materials[index];
  19190. }
  19191. }
  19192. return null;
  19193. };
  19194. Scene.prototype.getLensFlareSystemByName = function (name) {
  19195. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19196. if (this.lensFlareSystems[index].name === name) {
  19197. return this.lensFlareSystems[index];
  19198. }
  19199. }
  19200. return null;
  19201. };
  19202. Scene.prototype.getLensFlareSystemByID = function (id) {
  19203. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19204. if (this.lensFlareSystems[index].id === id) {
  19205. return this.lensFlareSystems[index];
  19206. }
  19207. }
  19208. return null;
  19209. };
  19210. Scene.prototype.getCameraByID = function (id) {
  19211. for (var index = 0; index < this.cameras.length; index++) {
  19212. if (this.cameras[index].id === id) {
  19213. return this.cameras[index];
  19214. }
  19215. }
  19216. return null;
  19217. };
  19218. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19219. for (var index = 0; index < this.cameras.length; index++) {
  19220. if (this.cameras[index].uniqueId === uniqueId) {
  19221. return this.cameras[index];
  19222. }
  19223. }
  19224. return null;
  19225. };
  19226. /**
  19227. * get a camera using its name
  19228. * @param {string} the camera's name
  19229. * @return {BABYLON.Camera|null} the camera or null if none found.
  19230. */
  19231. Scene.prototype.getCameraByName = function (name) {
  19232. for (var index = 0; index < this.cameras.length; index++) {
  19233. if (this.cameras[index].name === name) {
  19234. return this.cameras[index];
  19235. }
  19236. }
  19237. return null;
  19238. };
  19239. /**
  19240. * get a bone using its id
  19241. * @param {string} the bone's id
  19242. * @return {BABYLON.Bone|null} the bone or null if not found
  19243. */
  19244. Scene.prototype.getBoneByID = function (id) {
  19245. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19246. var skeleton = this.skeletons[skeletonIndex];
  19247. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19248. if (skeleton.bones[boneIndex].id === id) {
  19249. return skeleton.bones[boneIndex];
  19250. }
  19251. }
  19252. }
  19253. return null;
  19254. };
  19255. /**
  19256. * get a bone using its id
  19257. * @param {string} the bone's name
  19258. * @return {BABYLON.Bone|null} the bone or null if not found
  19259. */
  19260. Scene.prototype.getBoneByName = function (name) {
  19261. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19262. var skeleton = this.skeletons[skeletonIndex];
  19263. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19264. if (skeleton.bones[boneIndex].name === name) {
  19265. return skeleton.bones[boneIndex];
  19266. }
  19267. }
  19268. }
  19269. return null;
  19270. };
  19271. /**
  19272. * get a light node using its name
  19273. * @param {string} the light's name
  19274. * @return {BABYLON.Light|null} the light or null if none found.
  19275. */
  19276. Scene.prototype.getLightByName = function (name) {
  19277. for (var index = 0; index < this.lights.length; index++) {
  19278. if (this.lights[index].name === name) {
  19279. return this.lights[index];
  19280. }
  19281. }
  19282. return null;
  19283. };
  19284. /**
  19285. * get a light node using its ID
  19286. * @param {string} the light's id
  19287. * @return {BABYLON.Light|null} the light or null if none found.
  19288. */
  19289. Scene.prototype.getLightByID = function (id) {
  19290. for (var index = 0; index < this.lights.length; index++) {
  19291. if (this.lights[index].id === id) {
  19292. return this.lights[index];
  19293. }
  19294. }
  19295. return null;
  19296. };
  19297. /**
  19298. * get a light node using its scene-generated unique ID
  19299. * @param {number} the light's unique id
  19300. * @return {BABYLON.Light|null} the light or null if none found.
  19301. */
  19302. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19303. for (var index = 0; index < this.lights.length; index++) {
  19304. if (this.lights[index].uniqueId === uniqueId) {
  19305. return this.lights[index];
  19306. }
  19307. }
  19308. return null;
  19309. };
  19310. /**
  19311. * get a particle system by id
  19312. * @param id {number} the particle system id
  19313. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19314. */
  19315. Scene.prototype.getParticleSystemByID = function (id) {
  19316. for (var index = 0; index < this.particleSystems.length; index++) {
  19317. if (this.particleSystems[index].id === id) {
  19318. return this.particleSystems[index];
  19319. }
  19320. }
  19321. return null;
  19322. };
  19323. /**
  19324. * get a geometry using its ID
  19325. * @param {string} the geometry's id
  19326. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19327. */
  19328. Scene.prototype.getGeometryByID = function (id) {
  19329. for (var index = 0; index < this._geometries.length; index++) {
  19330. if (this._geometries[index].id === id) {
  19331. return this._geometries[index];
  19332. }
  19333. }
  19334. return null;
  19335. };
  19336. /**
  19337. * add a new geometry to this scene.
  19338. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19339. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19340. * @return {boolean} was the geometry added or not
  19341. */
  19342. Scene.prototype.pushGeometry = function (geometry, force) {
  19343. if (!force && this.getGeometryByID(geometry.id)) {
  19344. return false;
  19345. }
  19346. this._geometries.push(geometry);
  19347. //notify the collision coordinator
  19348. if (this.collisionCoordinator) {
  19349. this.collisionCoordinator.onGeometryAdded(geometry);
  19350. }
  19351. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19352. return true;
  19353. };
  19354. /**
  19355. * Removes an existing geometry
  19356. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19357. * @return {boolean} was the geometry removed or not
  19358. */
  19359. Scene.prototype.removeGeometry = function (geometry) {
  19360. var index = this._geometries.indexOf(geometry);
  19361. if (index > -1) {
  19362. this._geometries.splice(index, 1);
  19363. //notify the collision coordinator
  19364. if (this.collisionCoordinator) {
  19365. this.collisionCoordinator.onGeometryDeleted(geometry);
  19366. }
  19367. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19368. return true;
  19369. }
  19370. return false;
  19371. };
  19372. Scene.prototype.getGeometries = function () {
  19373. return this._geometries;
  19374. };
  19375. /**
  19376. * Get the first added mesh found of a given ID
  19377. * @param {string} id - the id to search for
  19378. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19379. */
  19380. Scene.prototype.getMeshByID = function (id) {
  19381. for (var index = 0; index < this.meshes.length; index++) {
  19382. if (this.meshes[index].id === id) {
  19383. return this.meshes[index];
  19384. }
  19385. }
  19386. return null;
  19387. };
  19388. Scene.prototype.getMeshesByID = function (id) {
  19389. return this.meshes.filter(function (m) {
  19390. return m.id === id;
  19391. });
  19392. };
  19393. /**
  19394. * Get a mesh with its auto-generated unique id
  19395. * @param {number} uniqueId - the unique id to search for
  19396. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19397. */
  19398. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19399. for (var index = 0; index < this.meshes.length; index++) {
  19400. if (this.meshes[index].uniqueId === uniqueId) {
  19401. return this.meshes[index];
  19402. }
  19403. }
  19404. return null;
  19405. };
  19406. /**
  19407. * Get a the last added mesh found of a given ID
  19408. * @param {string} id - the id to search for
  19409. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19410. */
  19411. Scene.prototype.getLastMeshByID = function (id) {
  19412. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19413. if (this.meshes[index].id === id) {
  19414. return this.meshes[index];
  19415. }
  19416. }
  19417. return null;
  19418. };
  19419. /**
  19420. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19421. * @param {string} id - the id to search for
  19422. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19423. */
  19424. Scene.prototype.getLastEntryByID = function (id) {
  19425. var index;
  19426. for (index = this.meshes.length - 1; index >= 0; index--) {
  19427. if (this.meshes[index].id === id) {
  19428. return this.meshes[index];
  19429. }
  19430. }
  19431. for (index = this.cameras.length - 1; index >= 0; index--) {
  19432. if (this.cameras[index].id === id) {
  19433. return this.cameras[index];
  19434. }
  19435. }
  19436. for (index = this.lights.length - 1; index >= 0; index--) {
  19437. if (this.lights[index].id === id) {
  19438. return this.lights[index];
  19439. }
  19440. }
  19441. return null;
  19442. };
  19443. Scene.prototype.getNodeByID = function (id) {
  19444. var mesh = this.getMeshByID(id);
  19445. if (mesh) {
  19446. return mesh;
  19447. }
  19448. var light = this.getLightByID(id);
  19449. if (light) {
  19450. return light;
  19451. }
  19452. var camera = this.getCameraByID(id);
  19453. if (camera) {
  19454. return camera;
  19455. }
  19456. var bone = this.getBoneByID(id);
  19457. return bone;
  19458. };
  19459. Scene.prototype.getNodeByName = function (name) {
  19460. var mesh = this.getMeshByName(name);
  19461. if (mesh) {
  19462. return mesh;
  19463. }
  19464. var light = this.getLightByName(name);
  19465. if (light) {
  19466. return light;
  19467. }
  19468. var camera = this.getCameraByName(name);
  19469. if (camera) {
  19470. return camera;
  19471. }
  19472. var bone = this.getBoneByName(name);
  19473. return bone;
  19474. };
  19475. Scene.prototype.getMeshByName = function (name) {
  19476. for (var index = 0; index < this.meshes.length; index++) {
  19477. if (this.meshes[index].name === name) {
  19478. return this.meshes[index];
  19479. }
  19480. }
  19481. return null;
  19482. };
  19483. Scene.prototype.getSoundByName = function (name) {
  19484. var index;
  19485. if (BABYLON.AudioEngine) {
  19486. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19487. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19488. return this.mainSoundTrack.soundCollection[index];
  19489. }
  19490. }
  19491. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19492. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19493. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19494. return this.soundTracks[sdIndex].soundCollection[index];
  19495. }
  19496. }
  19497. }
  19498. }
  19499. return null;
  19500. };
  19501. Scene.prototype.getLastSkeletonByID = function (id) {
  19502. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19503. if (this.skeletons[index].id === id) {
  19504. return this.skeletons[index];
  19505. }
  19506. }
  19507. return null;
  19508. };
  19509. Scene.prototype.getSkeletonById = function (id) {
  19510. for (var index = 0; index < this.skeletons.length; index++) {
  19511. if (this.skeletons[index].id === id) {
  19512. return this.skeletons[index];
  19513. }
  19514. }
  19515. return null;
  19516. };
  19517. Scene.prototype.getSkeletonByName = function (name) {
  19518. for (var index = 0; index < this.skeletons.length; index++) {
  19519. if (this.skeletons[index].name === name) {
  19520. return this.skeletons[index];
  19521. }
  19522. }
  19523. return null;
  19524. };
  19525. Scene.prototype.getMorphTargetManagerById = function (id) {
  19526. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19527. if (this.morphTargetManagers[index].uniqueId === id) {
  19528. return this.morphTargetManagers[index];
  19529. }
  19530. }
  19531. return null;
  19532. };
  19533. Scene.prototype.isActiveMesh = function (mesh) {
  19534. return (this._activeMeshes.indexOf(mesh) !== -1);
  19535. };
  19536. /**
  19537. * Return a the first highlight layer of the scene with a given name.
  19538. * @param name The name of the highlight layer to look for.
  19539. * @return The highlight layer if found otherwise null.
  19540. */
  19541. Scene.prototype.getHighlightLayerByName = function (name) {
  19542. for (var index = 0; index < this.highlightLayers.length; index++) {
  19543. if (this.highlightLayers[index].name === name) {
  19544. return this.highlightLayers[index];
  19545. }
  19546. }
  19547. return null;
  19548. };
  19549. Object.defineProperty(Scene.prototype, "uid", {
  19550. /**
  19551. * Return a unique id as a string which can serve as an identifier for the scene
  19552. */
  19553. get: function () {
  19554. if (!this._uid) {
  19555. this._uid = BABYLON.Tools.RandomId();
  19556. }
  19557. return this._uid;
  19558. },
  19559. enumerable: true,
  19560. configurable: true
  19561. });
  19562. /**
  19563. * Add an externaly attached data from its key.
  19564. * This method call will fail and return false, if such key already exists.
  19565. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  19566. * @param key the unique key that identifies the data
  19567. * @param data the data object to associate to the key for this Engine instance
  19568. * @return true if no such key were already present and the data was added successfully, false otherwise
  19569. */
  19570. Scene.prototype.addExternalData = function (key, data) {
  19571. if (!this._externalData) {
  19572. this._externalData = new BABYLON.StringDictionary();
  19573. }
  19574. return this._externalData.add(key, data);
  19575. };
  19576. /**
  19577. * Get an externaly attached data from its key
  19578. * @param key the unique key that identifies the data
  19579. * @return the associated data, if present (can be null), or undefined if not present
  19580. */
  19581. Scene.prototype.getExternalData = function (key) {
  19582. if (!this._externalData) {
  19583. return null;
  19584. }
  19585. return this._externalData.get(key);
  19586. };
  19587. /**
  19588. * Get an externaly attached data from its key, create it using a factory if it's not already present
  19589. * @param key the unique key that identifies the data
  19590. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  19591. * @return the associated data, can be null if the factory returned null.
  19592. */
  19593. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  19594. if (!this._externalData) {
  19595. this._externalData = new BABYLON.StringDictionary();
  19596. }
  19597. return this._externalData.getOrAddWithFactory(key, factory);
  19598. };
  19599. /**
  19600. * Remove an externaly attached data from the Engine instance
  19601. * @param key the unique key that identifies the data
  19602. * @return true if the data was successfully removed, false if it doesn't exist
  19603. */
  19604. Scene.prototype.removeExternalData = function (key) {
  19605. return this._externalData.remove(key);
  19606. };
  19607. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  19608. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  19609. var material = subMesh.getMaterial();
  19610. if (mesh.showSubMeshesBoundingBox) {
  19611. var boundingInfo = subMesh.getBoundingInfo();
  19612. if (boundingInfo) {
  19613. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19614. }
  19615. }
  19616. if (material) {
  19617. // Render targets
  19618. if (material.getRenderTargetTextures) {
  19619. if (this._processedMaterials.indexOf(material) === -1) {
  19620. this._processedMaterials.push(material);
  19621. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19622. }
  19623. }
  19624. // Dispatch
  19625. this._activeIndices.addCount(subMesh.indexCount, false);
  19626. this._renderingManager.dispatch(subMesh);
  19627. }
  19628. }
  19629. };
  19630. Scene.prototype._isInIntermediateRendering = function () {
  19631. return this._intermediateRendering;
  19632. };
  19633. /**
  19634. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  19635. */
  19636. Scene.prototype.freezeActiveMeshes = function () {
  19637. this._evaluateActiveMeshes();
  19638. this._activeMeshesFrozen = true;
  19639. return this;
  19640. };
  19641. /**
  19642. * Use this function to restart evaluating active meshes on every frame
  19643. */
  19644. Scene.prototype.unfreezeActiveMeshes = function () {
  19645. this._activeMeshesFrozen = false;
  19646. return this;
  19647. };
  19648. Scene.prototype._evaluateActiveMeshes = function () {
  19649. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  19650. return;
  19651. }
  19652. if (!this.activeCamera) {
  19653. return;
  19654. }
  19655. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  19656. this.activeCamera._activeMeshes.reset();
  19657. this._activeMeshes.reset();
  19658. this._renderingManager.reset();
  19659. this._processedMaterials.reset();
  19660. this._activeParticleSystems.reset();
  19661. this._activeSkeletons.reset();
  19662. this._softwareSkinnedMeshes.reset();
  19663. if (this._boundingBoxRenderer) {
  19664. this._boundingBoxRenderer.reset();
  19665. }
  19666. // Meshes
  19667. var meshes;
  19668. var len;
  19669. if (this._selectionOctree) {
  19670. var selection = this._selectionOctree.select(this._frustumPlanes);
  19671. meshes = selection.data;
  19672. len = selection.length;
  19673. }
  19674. else {
  19675. len = this.meshes.length;
  19676. meshes = this.meshes;
  19677. }
  19678. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19679. var mesh = meshes[meshIndex];
  19680. if (mesh.isBlocked) {
  19681. continue;
  19682. }
  19683. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19684. if (!mesh.isReady() || !mesh.isEnabled()) {
  19685. continue;
  19686. }
  19687. mesh.computeWorldMatrix();
  19688. // Intersections
  19689. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19690. this._meshesForIntersections.pushNoDuplicate(mesh);
  19691. }
  19692. // Switch to current LOD
  19693. var meshLOD = mesh.getLOD(this.activeCamera);
  19694. if (!meshLOD) {
  19695. continue;
  19696. }
  19697. mesh._preActivate();
  19698. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19699. this._activeMeshes.push(mesh);
  19700. this.activeCamera._activeMeshes.push(mesh);
  19701. mesh._activate(this._renderId);
  19702. if (meshLOD !== mesh) {
  19703. meshLOD._activate(this._renderId);
  19704. }
  19705. this._activeMesh(mesh, meshLOD);
  19706. }
  19707. }
  19708. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  19709. // Particle systems
  19710. if (this.particlesEnabled) {
  19711. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  19712. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19713. var particleSystem = this.particleSystems[particleIndex];
  19714. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19715. continue;
  19716. }
  19717. var emitter = particleSystem.emitter;
  19718. if (!emitter.position || emitter.isEnabled()) {
  19719. this._activeParticleSystems.push(particleSystem);
  19720. particleSystem.animate();
  19721. this._renderingManager.dispatchParticles(particleSystem);
  19722. }
  19723. }
  19724. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  19725. }
  19726. };
  19727. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19728. if (mesh.skeleton && this.skeletonsEnabled) {
  19729. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19730. mesh.skeleton.prepare();
  19731. }
  19732. if (!mesh.computeBonesUsingShaders) {
  19733. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19734. }
  19735. }
  19736. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19737. var boundingInfo = sourceMesh.getBoundingInfo();
  19738. if (boundingInfo) {
  19739. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19740. }
  19741. }
  19742. if (mesh && mesh.subMeshes) {
  19743. // Submeshes Octrees
  19744. var len;
  19745. var subMeshes;
  19746. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19747. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19748. len = intersections.length;
  19749. subMeshes = intersections.data;
  19750. }
  19751. else {
  19752. subMeshes = mesh.subMeshes;
  19753. len = subMeshes.length;
  19754. }
  19755. for (var subIndex = 0; subIndex < len; subIndex++) {
  19756. var subMesh = subMeshes[subIndex];
  19757. this._evaluateSubMesh(subMesh, mesh);
  19758. }
  19759. }
  19760. };
  19761. Scene.prototype.updateTransformMatrix = function (force) {
  19762. if (!this.activeCamera) {
  19763. return;
  19764. }
  19765. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19766. };
  19767. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19768. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19769. };
  19770. Scene.prototype._renderForCamera = function (camera) {
  19771. if (camera && camera._skipRendering) {
  19772. return;
  19773. }
  19774. var engine = this._engine;
  19775. this.activeCamera = camera;
  19776. if (!this.activeCamera)
  19777. throw new Error("Active camera not set");
  19778. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19779. // Viewport
  19780. engine.setViewport(this.activeCamera.viewport);
  19781. // Camera
  19782. this.resetCachedMaterial();
  19783. this._renderId++;
  19784. this.activeCamera.update();
  19785. this.updateTransformMatrix();
  19786. if (camera._alternateCamera) {
  19787. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19788. this._alternateRendering = true;
  19789. }
  19790. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19791. // Meshes
  19792. this._evaluateActiveMeshes();
  19793. // Software skinning
  19794. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19795. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19796. mesh.applySkeleton(mesh.skeleton);
  19797. }
  19798. // Render targets
  19799. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19800. var needsRestoreFrameBuffer = false;
  19801. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19802. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19803. }
  19804. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19805. this._intermediateRendering = true;
  19806. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19807. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19808. var renderTarget = this._renderTargets.data[renderIndex];
  19809. if (renderTarget._shouldRender()) {
  19810. this._renderId++;
  19811. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19812. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19813. }
  19814. }
  19815. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19816. this._intermediateRendering = false;
  19817. this._renderId++;
  19818. needsRestoreFrameBuffer = true; // Restore back buffer
  19819. }
  19820. // Render HighlightLayer Texture
  19821. var stencilState = this._engine.getStencilBuffer();
  19822. var renderhighlights = false;
  19823. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19824. this._intermediateRendering = true;
  19825. for (var i = 0; i < this.highlightLayers.length; i++) {
  19826. var highlightLayer = this.highlightLayers[i];
  19827. if (highlightLayer.shouldRender() &&
  19828. (!highlightLayer.camera ||
  19829. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19830. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19831. renderhighlights = true;
  19832. var renderTarget = highlightLayer._mainTexture;
  19833. if (renderTarget._shouldRender()) {
  19834. this._renderId++;
  19835. renderTarget.render(false, false);
  19836. needsRestoreFrameBuffer = true;
  19837. }
  19838. }
  19839. }
  19840. this._intermediateRendering = false;
  19841. this._renderId++;
  19842. }
  19843. if (needsRestoreFrameBuffer) {
  19844. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19845. }
  19846. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  19847. // Prepare Frame
  19848. this.postProcessManager._prepareFrame();
  19849. // Backgrounds
  19850. var layerIndex;
  19851. var layer;
  19852. if (this.layers.length) {
  19853. engine.setDepthBuffer(false);
  19854. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19855. layer = this.layers[layerIndex];
  19856. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19857. layer.render();
  19858. }
  19859. }
  19860. engine.setDepthBuffer(true);
  19861. }
  19862. // Activate HighlightLayer stencil
  19863. if (renderhighlights) {
  19864. this._engine.setStencilBuffer(true);
  19865. }
  19866. // Render
  19867. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  19868. this._renderingManager.render(null, null, true, true);
  19869. this.onAfterDrawPhaseObservable.notifyObservers(this);
  19870. // Restore HighlightLayer stencil
  19871. if (renderhighlights) {
  19872. this._engine.setStencilBuffer(stencilState);
  19873. }
  19874. // Bounding boxes
  19875. if (this._boundingBoxRenderer) {
  19876. this._boundingBoxRenderer.render();
  19877. }
  19878. // Lens flares
  19879. if (this.lensFlaresEnabled) {
  19880. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19881. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19882. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19883. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19884. lensFlareSystem.render();
  19885. }
  19886. }
  19887. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19888. }
  19889. // Foregrounds
  19890. if (this.layers.length) {
  19891. engine.setDepthBuffer(false);
  19892. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19893. layer = this.layers[layerIndex];
  19894. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19895. layer.render();
  19896. }
  19897. }
  19898. engine.setDepthBuffer(true);
  19899. }
  19900. // Highlight Layer
  19901. if (renderhighlights) {
  19902. engine.setDepthBuffer(false);
  19903. for (var i = 0; i < this.highlightLayers.length; i++) {
  19904. if (this.highlightLayers[i].shouldRender()) {
  19905. this.highlightLayers[i].render();
  19906. }
  19907. }
  19908. engine.setDepthBuffer(true);
  19909. }
  19910. // Finalize frame
  19911. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19912. // Reset some special arrays
  19913. this._renderTargets.reset();
  19914. this._alternateRendering = false;
  19915. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19916. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19917. };
  19918. Scene.prototype._processSubCameras = function (camera) {
  19919. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19920. this._renderForCamera(camera);
  19921. return;
  19922. }
  19923. // Update camera
  19924. if (this.activeCamera) {
  19925. this.activeCamera.update();
  19926. }
  19927. // rig cameras
  19928. for (var index = 0; index < camera._rigCameras.length; index++) {
  19929. this._renderForCamera(camera._rigCameras[index]);
  19930. }
  19931. this.activeCamera = camera;
  19932. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19933. };
  19934. Scene.prototype._checkIntersections = function () {
  19935. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19936. var sourceMesh = this._meshesForIntersections.data[index];
  19937. if (!sourceMesh.actionManager) {
  19938. continue;
  19939. }
  19940. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19941. var action = sourceMesh.actionManager.actions[actionIndex];
  19942. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19943. var parameters = action.getTriggerParameter();
  19944. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19945. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19946. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19947. if (areIntersecting && currentIntersectionInProgress === -1) {
  19948. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19949. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19950. sourceMesh._intersectionsInProgress.push(otherMesh);
  19951. }
  19952. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19953. sourceMesh._intersectionsInProgress.push(otherMesh);
  19954. }
  19955. }
  19956. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19957. //They intersected, and now they don't.
  19958. //is this trigger an exit trigger? execute an event.
  19959. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19960. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19961. }
  19962. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19963. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19964. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19965. }
  19966. }
  19967. }
  19968. }
  19969. }
  19970. };
  19971. Scene.prototype.render = function () {
  19972. if (this.isDisposed) {
  19973. return;
  19974. }
  19975. this._activeParticles.fetchNewFrame();
  19976. this._totalVertices.fetchNewFrame();
  19977. this._activeIndices.fetchNewFrame();
  19978. this._activeBones.fetchNewFrame();
  19979. this._meshesForIntersections.reset();
  19980. this.resetCachedMaterial();
  19981. this.onBeforeAnimationsObservable.notifyObservers(this);
  19982. // Actions
  19983. if (this.actionManager) {
  19984. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  19985. }
  19986. //Simplification Queue
  19987. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19988. this.simplificationQueue.executeNext();
  19989. }
  19990. if (this._engine.isDeterministicLockStep()) {
  19991. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19992. var defaultTimeStep = (60.0 / 1000.0);
  19993. if (this._physicsEngine) {
  19994. defaultTimeStep = this._physicsEngine.getTimeStep();
  19995. }
  19996. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19997. this._timeAccumulator += deltaTime;
  19998. // compute the amount of fixed steps we should have taken since the last step
  19999. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  20000. internalSteps = Math.min(internalSteps, maxSubSteps);
  20001. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  20002. this.onBeforeStepObservable.notifyObservers(this);
  20003. // Animations
  20004. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  20005. this._animate();
  20006. this.onAfterAnimationsObservable.notifyObservers(this);
  20007. // Physics
  20008. if (this._physicsEngine) {
  20009. this.onBeforePhysicsObservable.notifyObservers(this);
  20010. this._physicsEngine._step(defaultTimeStep);
  20011. this.onAfterPhysicsObservable.notifyObservers(this);
  20012. }
  20013. this._timeAccumulator -= defaultTimeStep;
  20014. this.onAfterStepObservable.notifyObservers(this);
  20015. this._currentStepId++;
  20016. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  20017. this._evaluateActiveMeshes();
  20018. }
  20019. }
  20020. }
  20021. else {
  20022. // Animations
  20023. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20024. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20025. this._animate();
  20026. this.onAfterAnimationsObservable.notifyObservers(this);
  20027. // Physics
  20028. if (this._physicsEngine) {
  20029. this.onBeforePhysicsObservable.notifyObservers(this);
  20030. this._physicsEngine._step(deltaTime / 1000.0);
  20031. this.onAfterPhysicsObservable.notifyObservers(this);
  20032. }
  20033. }
  20034. // Before render
  20035. this.onBeforeRenderObservable.notifyObservers(this);
  20036. // Customs render targets
  20037. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20038. var engine = this.getEngine();
  20039. var currentActiveCamera = this.activeCamera;
  20040. if (this.renderTargetsEnabled) {
  20041. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20042. this._intermediateRendering = true;
  20043. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20044. var renderTarget = this.customRenderTargets[customIndex];
  20045. if (renderTarget._shouldRender()) {
  20046. this._renderId++;
  20047. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20048. if (!this.activeCamera)
  20049. throw new Error("Active camera not set");
  20050. // Viewport
  20051. engine.setViewport(this.activeCamera.viewport);
  20052. // Camera
  20053. this.updateTransformMatrix();
  20054. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20055. }
  20056. }
  20057. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20058. this._intermediateRendering = false;
  20059. this._renderId++;
  20060. }
  20061. // Restore back buffer
  20062. if (this.customRenderTargets.length > 0) {
  20063. engine.restoreDefaultFramebuffer();
  20064. }
  20065. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20066. this.activeCamera = currentActiveCamera;
  20067. // Procedural textures
  20068. if (this.proceduralTexturesEnabled) {
  20069. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20070. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20071. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20072. if (proceduralTexture._shouldRender()) {
  20073. proceduralTexture.render();
  20074. }
  20075. }
  20076. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20077. }
  20078. // Clear
  20079. if (this.autoClearDepthAndStencil || this.autoClear) {
  20080. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20081. }
  20082. // Shadows
  20083. if (this.shadowsEnabled) {
  20084. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20085. var light = this.lights[lightIndex];
  20086. var shadowGenerator = light.getShadowGenerator();
  20087. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20088. var shadowMap = (shadowGenerator.getShadowMap());
  20089. if (this.textures.indexOf(shadowMap) !== -1) {
  20090. this._renderTargets.push(shadowMap);
  20091. }
  20092. }
  20093. }
  20094. }
  20095. // Depth renderer
  20096. if (this._depthRenderer) {
  20097. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20098. }
  20099. // Geometry renderer
  20100. if (this._geometryBufferRenderer) {
  20101. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20102. }
  20103. // RenderPipeline
  20104. if (this._postProcessRenderPipelineManager) {
  20105. this._postProcessRenderPipelineManager.update();
  20106. }
  20107. // Multi-cameras?
  20108. if (this.activeCameras.length > 0) {
  20109. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20110. if (cameraIndex > 0) {
  20111. this._engine.clear(null, false, true, true);
  20112. }
  20113. this._processSubCameras(this.activeCameras[cameraIndex]);
  20114. }
  20115. }
  20116. else {
  20117. if (!this.activeCamera) {
  20118. throw new Error("No camera defined");
  20119. }
  20120. this._processSubCameras(this.activeCamera);
  20121. }
  20122. // Intersection checks
  20123. this._checkIntersections();
  20124. // Update the audio listener attached to the camera
  20125. if (BABYLON.AudioEngine) {
  20126. this._updateAudioParameters();
  20127. }
  20128. // After render
  20129. if (this.afterRender) {
  20130. this.afterRender();
  20131. }
  20132. this.onAfterRenderObservable.notifyObservers(this);
  20133. // Cleaning
  20134. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20135. var data = this._toBeDisposed.data[index];
  20136. if (data) {
  20137. data.dispose();
  20138. }
  20139. this._toBeDisposed[index] = null;
  20140. }
  20141. this._toBeDisposed.reset();
  20142. if (this.dumpNextRenderTargets) {
  20143. this.dumpNextRenderTargets = false;
  20144. }
  20145. this._activeBones.addCount(0, true);
  20146. this._activeIndices.addCount(0, true);
  20147. this._activeParticles.addCount(0, true);
  20148. };
  20149. Scene.prototype._updateAudioParameters = function () {
  20150. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20151. return;
  20152. }
  20153. var listeningCamera;
  20154. var audioEngine = BABYLON.Engine.audioEngine;
  20155. if (this.activeCameras.length > 0) {
  20156. listeningCamera = this.activeCameras[0];
  20157. }
  20158. else {
  20159. listeningCamera = this.activeCamera;
  20160. }
  20161. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20162. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20163. // for VR cameras
  20164. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20165. listeningCamera = listeningCamera.rigCameras[0];
  20166. }
  20167. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20168. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20169. cameraDirection.normalize();
  20170. // To avoid some errors on GearVR
  20171. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20172. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20173. }
  20174. var i;
  20175. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20176. var sound = this.mainSoundTrack.soundCollection[i];
  20177. if (sound.useCustomAttenuation) {
  20178. sound.updateDistanceFromListener();
  20179. }
  20180. }
  20181. for (i = 0; i < this.soundTracks.length; i++) {
  20182. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20183. sound = this.soundTracks[i].soundCollection[j];
  20184. if (sound.useCustomAttenuation) {
  20185. sound.updateDistanceFromListener();
  20186. }
  20187. }
  20188. }
  20189. }
  20190. };
  20191. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20192. // Audio
  20193. get: function () {
  20194. return this._audioEnabled;
  20195. },
  20196. set: function (value) {
  20197. this._audioEnabled = value;
  20198. if (BABYLON.AudioEngine) {
  20199. if (this._audioEnabled) {
  20200. this._enableAudio();
  20201. }
  20202. else {
  20203. this._disableAudio();
  20204. }
  20205. }
  20206. },
  20207. enumerable: true,
  20208. configurable: true
  20209. });
  20210. Scene.prototype._disableAudio = function () {
  20211. var i;
  20212. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20213. this.mainSoundTrack.soundCollection[i].pause();
  20214. }
  20215. for (i = 0; i < this.soundTracks.length; i++) {
  20216. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20217. this.soundTracks[i].soundCollection[j].pause();
  20218. }
  20219. }
  20220. };
  20221. Scene.prototype._enableAudio = function () {
  20222. var i;
  20223. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20224. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20225. this.mainSoundTrack.soundCollection[i].play();
  20226. }
  20227. }
  20228. for (i = 0; i < this.soundTracks.length; i++) {
  20229. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20230. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20231. this.soundTracks[i].soundCollection[j].play();
  20232. }
  20233. }
  20234. }
  20235. };
  20236. Object.defineProperty(Scene.prototype, "headphone", {
  20237. get: function () {
  20238. return this._headphone;
  20239. },
  20240. set: function (value) {
  20241. this._headphone = value;
  20242. if (BABYLON.AudioEngine) {
  20243. if (this._headphone) {
  20244. this._switchAudioModeForHeadphones();
  20245. }
  20246. else {
  20247. this._switchAudioModeForNormalSpeakers();
  20248. }
  20249. }
  20250. },
  20251. enumerable: true,
  20252. configurable: true
  20253. });
  20254. Scene.prototype._switchAudioModeForHeadphones = function () {
  20255. this.mainSoundTrack.switchPanningModelToHRTF();
  20256. for (var i = 0; i < this.soundTracks.length; i++) {
  20257. this.soundTracks[i].switchPanningModelToHRTF();
  20258. }
  20259. };
  20260. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20261. this.mainSoundTrack.switchPanningModelToEqualPower();
  20262. for (var i = 0; i < this.soundTracks.length; i++) {
  20263. this.soundTracks[i].switchPanningModelToEqualPower();
  20264. }
  20265. };
  20266. Scene.prototype.enableDepthRenderer = function () {
  20267. if (this._depthRenderer) {
  20268. return this._depthRenderer;
  20269. }
  20270. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20271. return this._depthRenderer;
  20272. };
  20273. Scene.prototype.disableDepthRenderer = function () {
  20274. if (!this._depthRenderer) {
  20275. return;
  20276. }
  20277. this._depthRenderer.dispose();
  20278. this._depthRenderer = null;
  20279. };
  20280. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20281. if (ratio === void 0) { ratio = 1; }
  20282. if (this._geometryBufferRenderer) {
  20283. return this._geometryBufferRenderer;
  20284. }
  20285. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20286. if (!this._geometryBufferRenderer.isSupported) {
  20287. this._geometryBufferRenderer = null;
  20288. }
  20289. return this._geometryBufferRenderer;
  20290. };
  20291. Scene.prototype.disableGeometryBufferRenderer = function () {
  20292. if (!this._geometryBufferRenderer) {
  20293. return;
  20294. }
  20295. this._geometryBufferRenderer.dispose();
  20296. this._geometryBufferRenderer = null;
  20297. };
  20298. Scene.prototype.freezeMaterials = function () {
  20299. for (var i = 0; i < this.materials.length; i++) {
  20300. this.materials[i].freeze();
  20301. }
  20302. };
  20303. Scene.prototype.unfreezeMaterials = function () {
  20304. for (var i = 0; i < this.materials.length; i++) {
  20305. this.materials[i].unfreeze();
  20306. }
  20307. };
  20308. Scene.prototype.dispose = function () {
  20309. this.beforeRender = null;
  20310. this.afterRender = null;
  20311. this.skeletons = [];
  20312. this.morphTargetManagers = [];
  20313. this.importedMeshesFiles = new Array();
  20314. this.resetCachedMaterial();
  20315. if (this._depthRenderer) {
  20316. this._depthRenderer.dispose();
  20317. }
  20318. if (this._gamepadManager) {
  20319. this._gamepadManager.dispose();
  20320. this._gamepadManager = null;
  20321. }
  20322. // Smart arrays
  20323. if (this.activeCamera) {
  20324. this.activeCamera._activeMeshes.dispose();
  20325. this.activeCamera = null;
  20326. }
  20327. this._activeMeshes.dispose();
  20328. this._renderingManager.dispose();
  20329. this._processedMaterials.dispose();
  20330. this._activeParticleSystems.dispose();
  20331. this._activeSkeletons.dispose();
  20332. this._softwareSkinnedMeshes.dispose();
  20333. this._renderTargets.dispose();
  20334. if (this._boundingBoxRenderer) {
  20335. this._boundingBoxRenderer.dispose();
  20336. }
  20337. this._meshesForIntersections.dispose();
  20338. this._toBeDisposed.dispose();
  20339. // Debug layer
  20340. if (this._debugLayer) {
  20341. this._debugLayer.hide();
  20342. }
  20343. // Events
  20344. this.onDisposeObservable.notifyObservers(this);
  20345. this.onDisposeObservable.clear();
  20346. this.onBeforeRenderObservable.clear();
  20347. this.onAfterRenderObservable.clear();
  20348. this.OnBeforeRenderTargetsRenderObservable.clear();
  20349. this.OnAfterRenderTargetsRenderObservable.clear();
  20350. this.onAfterStepObservable.clear();
  20351. this.onBeforeStepObservable.clear();
  20352. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20353. this.onAfterActiveMeshesEvaluationObservable.clear();
  20354. this.onBeforeParticlesRenderingObservable.clear();
  20355. this.onAfterParticlesRenderingObservable.clear();
  20356. this.onBeforeSpritesRenderingObservable.clear();
  20357. this.onAfterSpritesRenderingObservable.clear();
  20358. this.onBeforeDrawPhaseObservable.clear();
  20359. this.onAfterDrawPhaseObservable.clear();
  20360. this.onBeforePhysicsObservable.clear();
  20361. this.onAfterPhysicsObservable.clear();
  20362. this.onBeforeAnimationsObservable.clear();
  20363. this.onAfterAnimationsObservable.clear();
  20364. this.detachControl();
  20365. // Release sounds & sounds tracks
  20366. if (BABYLON.AudioEngine) {
  20367. this.disposeSounds();
  20368. }
  20369. // VR Helper
  20370. if (this.VRHelper) {
  20371. this.VRHelper.dispose();
  20372. }
  20373. // Detach cameras
  20374. var canvas = this._engine.getRenderingCanvas();
  20375. if (canvas) {
  20376. var index;
  20377. for (index = 0; index < this.cameras.length; index++) {
  20378. this.cameras[index].detachControl(canvas);
  20379. }
  20380. }
  20381. // Release lights
  20382. while (this.lights.length) {
  20383. this.lights[0].dispose();
  20384. }
  20385. // Release meshes
  20386. while (this.meshes.length) {
  20387. this.meshes[0].dispose(true);
  20388. }
  20389. // Release cameras
  20390. while (this.cameras.length) {
  20391. this.cameras[0].dispose();
  20392. }
  20393. // Release materials
  20394. if (this.defaultMaterial) {
  20395. this.defaultMaterial.dispose();
  20396. }
  20397. while (this.multiMaterials.length) {
  20398. this.multiMaterials[0].dispose();
  20399. }
  20400. while (this.materials.length) {
  20401. this.materials[0].dispose();
  20402. }
  20403. // Release particles
  20404. while (this.particleSystems.length) {
  20405. this.particleSystems[0].dispose();
  20406. }
  20407. // Release sprites
  20408. while (this.spriteManagers.length) {
  20409. this.spriteManagers[0].dispose();
  20410. }
  20411. // Release postProcesses
  20412. while (this.postProcesses.length) {
  20413. this.postProcesses[0].dispose();
  20414. }
  20415. // Release layers
  20416. while (this.layers.length) {
  20417. this.layers[0].dispose();
  20418. }
  20419. while (this.highlightLayers.length) {
  20420. this.highlightLayers[0].dispose();
  20421. }
  20422. // Release textures
  20423. while (this.textures.length) {
  20424. this.textures[0].dispose();
  20425. }
  20426. // Release UBO
  20427. this._sceneUbo.dispose();
  20428. if (this._alternateSceneUbo) {
  20429. this._alternateSceneUbo.dispose();
  20430. }
  20431. // Post-processes
  20432. this.postProcessManager.dispose();
  20433. if (this._postProcessRenderPipelineManager) {
  20434. this._postProcessRenderPipelineManager.dispose();
  20435. }
  20436. // Physics
  20437. if (this._physicsEngine) {
  20438. this.disablePhysicsEngine();
  20439. }
  20440. // Remove from engine
  20441. index = this._engine.scenes.indexOf(this);
  20442. if (index > -1) {
  20443. this._engine.scenes.splice(index, 1);
  20444. }
  20445. this._engine.wipeCaches();
  20446. this._isDisposed = true;
  20447. };
  20448. Object.defineProperty(Scene.prototype, "isDisposed", {
  20449. get: function () {
  20450. return this._isDisposed;
  20451. },
  20452. enumerable: true,
  20453. configurable: true
  20454. });
  20455. // Release sounds & sounds tracks
  20456. Scene.prototype.disposeSounds = function () {
  20457. if (!this._mainSoundTrack) {
  20458. return;
  20459. }
  20460. this.mainSoundTrack.dispose();
  20461. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20462. this.soundTracks[scIndex].dispose();
  20463. }
  20464. };
  20465. // Octrees
  20466. Scene.prototype.getWorldExtends = function () {
  20467. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20468. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20469. for (var index = 0; index < this.meshes.length; index++) {
  20470. var mesh = this.meshes[index];
  20471. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20472. continue;
  20473. }
  20474. mesh.computeWorldMatrix(true);
  20475. var boundingInfo = mesh.getBoundingInfo();
  20476. if (boundingInfo) {
  20477. var minBox = boundingInfo.boundingBox.minimumWorld;
  20478. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20479. BABYLON.Tools.CheckExtends(minBox, min, max);
  20480. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20481. }
  20482. }
  20483. return {
  20484. min: min,
  20485. max: max
  20486. };
  20487. };
  20488. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20489. if (maxCapacity === void 0) { maxCapacity = 64; }
  20490. if (maxDepth === void 0) { maxDepth = 2; }
  20491. if (!this._selectionOctree) {
  20492. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20493. }
  20494. var worldExtends = this.getWorldExtends();
  20495. // Update octree
  20496. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20497. return this._selectionOctree;
  20498. };
  20499. // Picking
  20500. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20501. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20502. var engine = this._engine;
  20503. if (!camera) {
  20504. if (!this.activeCamera)
  20505. throw new Error("Active camera not set");
  20506. camera = this.activeCamera;
  20507. }
  20508. var cameraViewport = camera.viewport;
  20509. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20510. // Moving coordinates to local viewport world
  20511. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20512. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20513. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20514. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20515. };
  20516. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20517. if (!BABYLON.PickingInfo) {
  20518. return null;
  20519. }
  20520. var engine = this._engine;
  20521. if (!camera) {
  20522. if (!this.activeCamera)
  20523. throw new Error("Active camera not set");
  20524. camera = this.activeCamera;
  20525. }
  20526. var cameraViewport = camera.viewport;
  20527. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20528. var identity = BABYLON.Matrix.Identity();
  20529. // Moving coordinates to local viewport world
  20530. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20531. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20532. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  20533. };
  20534. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  20535. if (!BABYLON.PickingInfo) {
  20536. return null;
  20537. }
  20538. var pickingInfo = null;
  20539. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20540. var mesh = this.meshes[meshIndex];
  20541. if (predicate) {
  20542. if (!predicate(mesh)) {
  20543. continue;
  20544. }
  20545. }
  20546. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20547. continue;
  20548. }
  20549. var world = mesh.getWorldMatrix();
  20550. var ray = rayFunction(world);
  20551. var result = mesh.intersects(ray, fastCheck);
  20552. if (!result || !result.hit)
  20553. continue;
  20554. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20555. continue;
  20556. pickingInfo = result;
  20557. if (fastCheck) {
  20558. break;
  20559. }
  20560. }
  20561. return pickingInfo || new BABYLON.PickingInfo();
  20562. };
  20563. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  20564. if (!BABYLON.PickingInfo) {
  20565. return null;
  20566. }
  20567. var pickingInfos = new Array();
  20568. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20569. var mesh = this.meshes[meshIndex];
  20570. if (predicate) {
  20571. if (!predicate(mesh)) {
  20572. continue;
  20573. }
  20574. }
  20575. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20576. continue;
  20577. }
  20578. var world = mesh.getWorldMatrix();
  20579. var ray = rayFunction(world);
  20580. var result = mesh.intersects(ray, false);
  20581. if (!result || !result.hit)
  20582. continue;
  20583. pickingInfos.push(result);
  20584. }
  20585. return pickingInfos;
  20586. };
  20587. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  20588. if (!BABYLON.PickingInfo) {
  20589. return null;
  20590. }
  20591. var pickingInfo = null;
  20592. if (!camera) {
  20593. if (!this.activeCamera) {
  20594. return null;
  20595. }
  20596. camera = this.activeCamera;
  20597. }
  20598. if (this.spriteManagers.length > 0) {
  20599. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  20600. var spriteManager = this.spriteManagers[spriteIndex];
  20601. if (!spriteManager.isPickable) {
  20602. continue;
  20603. }
  20604. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  20605. if (!result || !result.hit)
  20606. continue;
  20607. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20608. continue;
  20609. pickingInfo = result;
  20610. if (fastCheck) {
  20611. break;
  20612. }
  20613. }
  20614. }
  20615. return pickingInfo || new BABYLON.PickingInfo();
  20616. };
  20617. /** Launch a ray to try to pick a mesh in the scene
  20618. * @param x position on screen
  20619. * @param y position on screen
  20620. * @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
  20621. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20622. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20623. */
  20624. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  20625. var _this = this;
  20626. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  20627. };
  20628. /** Launch a ray to try to pick a sprite in the scene
  20629. * @param x position on screen
  20630. * @param y position on screen
  20631. * @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
  20632. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20633. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20634. */
  20635. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  20636. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  20637. if (!ray) {
  20638. return null;
  20639. }
  20640. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  20641. };
  20642. /** Use the given ray to pick a mesh in the scene
  20643. * @param ray The ray to use to pick meshes
  20644. * @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
  20645. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20646. */
  20647. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  20648. var _this = this;
  20649. return this._internalPick(function (world) {
  20650. if (!_this._pickWithRayInverseMatrix) {
  20651. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20652. }
  20653. world.invertToRef(_this._pickWithRayInverseMatrix);
  20654. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20655. }, predicate, fastCheck);
  20656. };
  20657. /**
  20658. * Launch a ray to try to pick a mesh in the scene
  20659. * @param x X position on screen
  20660. * @param y Y position on screen
  20661. * @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
  20662. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20663. */
  20664. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  20665. var _this = this;
  20666. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  20667. };
  20668. /**
  20669. * Launch a ray to try to pick a mesh in the scene
  20670. * @param ray Ray to use
  20671. * @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
  20672. */
  20673. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  20674. var _this = this;
  20675. return this._internalMultiPick(function (world) {
  20676. if (!_this._pickWithRayInverseMatrix) {
  20677. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20678. }
  20679. world.invertToRef(_this._pickWithRayInverseMatrix);
  20680. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20681. }, predicate);
  20682. };
  20683. Scene.prototype.setPointerOverMesh = function (mesh) {
  20684. if (this._pointerOverMesh === mesh) {
  20685. return;
  20686. }
  20687. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20688. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20689. }
  20690. this._pointerOverMesh = mesh;
  20691. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20692. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20693. }
  20694. };
  20695. Scene.prototype.getPointerOverMesh = function () {
  20696. return this._pointerOverMesh;
  20697. };
  20698. Scene.prototype.setPointerOverSprite = function (sprite) {
  20699. if (this._pointerOverSprite === sprite) {
  20700. return;
  20701. }
  20702. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20703. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20704. }
  20705. this._pointerOverSprite = sprite;
  20706. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20707. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20708. }
  20709. };
  20710. Scene.prototype.getPointerOverSprite = function () {
  20711. return this._pointerOverSprite;
  20712. };
  20713. // Physics
  20714. Scene.prototype.getPhysicsEngine = function () {
  20715. return this._physicsEngine;
  20716. };
  20717. /**
  20718. * Enables physics to the current scene
  20719. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20720. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20721. * @return {boolean} was the physics engine initialized
  20722. */
  20723. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20724. if (gravity === void 0) { gravity = null; }
  20725. if (this._physicsEngine) {
  20726. return true;
  20727. }
  20728. try {
  20729. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20730. return true;
  20731. }
  20732. catch (e) {
  20733. BABYLON.Tools.Error(e.message);
  20734. return false;
  20735. }
  20736. };
  20737. Scene.prototype.disablePhysicsEngine = function () {
  20738. if (!this._physicsEngine) {
  20739. return;
  20740. }
  20741. this._physicsEngine.dispose();
  20742. this._physicsEngine = null;
  20743. };
  20744. Scene.prototype.isPhysicsEnabled = function () {
  20745. return this._physicsEngine !== undefined;
  20746. };
  20747. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20748. var mesh = compound.parts[0].mesh;
  20749. if (mesh.physicsImpostor) {
  20750. mesh.physicsImpostor.dispose();
  20751. mesh.physicsImpostor = null;
  20752. }
  20753. };
  20754. // Misc.
  20755. Scene.prototype._rebuildGeometries = function () {
  20756. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20757. var geometry = _a[_i];
  20758. geometry._rebuild();
  20759. }
  20760. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20761. var mesh = _c[_b];
  20762. mesh._rebuild();
  20763. }
  20764. if (this.postProcessManager) {
  20765. this.postProcessManager._rebuild();
  20766. }
  20767. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20768. var layer = _e[_d];
  20769. layer._rebuild();
  20770. }
  20771. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20772. var highlightLayer = _g[_f];
  20773. highlightLayer._rebuild();
  20774. }
  20775. if (this._boundingBoxRenderer) {
  20776. this._boundingBoxRenderer._rebuild();
  20777. }
  20778. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20779. var system = _j[_h];
  20780. system.rebuild();
  20781. }
  20782. if (this._postProcessRenderPipelineManager) {
  20783. this._postProcessRenderPipelineManager._rebuild();
  20784. }
  20785. };
  20786. Scene.prototype._rebuildTextures = function () {
  20787. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20788. var texture = _a[_i];
  20789. texture._rebuild();
  20790. }
  20791. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20792. };
  20793. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20794. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20795. if (replace === void 0) { replace = false; }
  20796. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20797. // Dispose existing camera or light in replace mode.
  20798. if (replace) {
  20799. if (this.activeCamera) {
  20800. this.activeCamera.dispose();
  20801. this.activeCamera = null;
  20802. }
  20803. if (this.lights) {
  20804. for (var i = 0; i < this.lights.length; i++) {
  20805. this.lights[i].dispose();
  20806. }
  20807. }
  20808. }
  20809. // Light
  20810. if (this.lights.length === 0) {
  20811. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20812. }
  20813. // Camera
  20814. if (!this.activeCamera) {
  20815. var worldExtends = this.getWorldExtends();
  20816. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20817. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20818. var camera;
  20819. var radius = worldSize.length() * 1.5;
  20820. if (createArcRotateCamera) {
  20821. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20822. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20823. arcRotateCamera.wheelPrecision = 100 / radius;
  20824. camera = arcRotateCamera;
  20825. }
  20826. else {
  20827. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20828. freeCamera.setTarget(worldCenter);
  20829. camera = freeCamera;
  20830. }
  20831. camera.minZ = radius * 0.01;
  20832. camera.maxZ = radius * 100;
  20833. camera.speed = radius * 0.2;
  20834. this.activeCamera = camera;
  20835. var canvas = this.getEngine().getRenderingCanvas();
  20836. if (attachCameraControls && canvas) {
  20837. camera.attachControl(canvas);
  20838. }
  20839. }
  20840. };
  20841. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20842. if (pbr === void 0) { pbr = false; }
  20843. if (scale === void 0) { scale = 1000; }
  20844. if (blur === void 0) { blur = 0; }
  20845. if (environmentTexture) {
  20846. this.environmentTexture = environmentTexture;
  20847. }
  20848. if (!this.environmentTexture) {
  20849. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20850. return null;
  20851. }
  20852. // Skybox
  20853. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20854. if (pbr) {
  20855. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20856. hdrSkyboxMaterial.backFaceCulling = false;
  20857. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20858. if (hdrSkyboxMaterial.reflectionTexture) {
  20859. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20860. }
  20861. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20862. hdrSkyboxMaterial.disableLighting = true;
  20863. hdrSkyboxMaterial.twoSidedLighting = true;
  20864. hdrSkybox.infiniteDistance = true;
  20865. hdrSkybox.material = hdrSkyboxMaterial;
  20866. }
  20867. else {
  20868. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20869. skyboxMaterial.backFaceCulling = false;
  20870. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20871. if (skyboxMaterial.reflectionTexture) {
  20872. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20873. }
  20874. skyboxMaterial.disableLighting = true;
  20875. hdrSkybox.infiniteDistance = true;
  20876. hdrSkybox.material = skyboxMaterial;
  20877. }
  20878. return hdrSkybox;
  20879. };
  20880. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20881. if (webVROptions === void 0) { webVROptions = {}; }
  20882. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20883. };
  20884. // Tags
  20885. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20886. if (tagsQuery === undefined) {
  20887. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20888. return list;
  20889. }
  20890. var listByTags = [];
  20891. forEach = forEach || (function (item) { return; });
  20892. for (var i in list) {
  20893. var item = list[i];
  20894. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20895. listByTags.push(item);
  20896. forEach(item);
  20897. }
  20898. }
  20899. return listByTags;
  20900. };
  20901. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20902. return this._getByTags(this.meshes, tagsQuery, forEach);
  20903. };
  20904. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20905. return this._getByTags(this.cameras, tagsQuery, forEach);
  20906. };
  20907. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20908. return this._getByTags(this.lights, tagsQuery, forEach);
  20909. };
  20910. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20911. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20912. };
  20913. /**
  20914. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20915. * This allowed control for front to back rendering or reversly depending of the special needs.
  20916. *
  20917. * @param renderingGroupId The rendering group id corresponding to its index
  20918. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20919. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20920. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20921. */
  20922. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20923. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20924. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20925. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20926. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20927. };
  20928. /**
  20929. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20930. *
  20931. * @param renderingGroupId The rendering group id corresponding to its index
  20932. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20933. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20934. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20935. */
  20936. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20937. if (depth === void 0) { depth = true; }
  20938. if (stencil === void 0) { stencil = true; }
  20939. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20940. };
  20941. /**
  20942. * Will flag all materials as dirty to trigger new shader compilation
  20943. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20944. */
  20945. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20946. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20947. var material = _a[_i];
  20948. if (predicate && !predicate(material)) {
  20949. continue;
  20950. }
  20951. material.markAsDirty(flag);
  20952. }
  20953. };
  20954. // Statics
  20955. Scene._FOGMODE_NONE = 0;
  20956. Scene._FOGMODE_EXP = 1;
  20957. Scene._FOGMODE_EXP2 = 2;
  20958. Scene._FOGMODE_LINEAR = 3;
  20959. Scene._uniqueIdCounter = 0;
  20960. Scene.MinDeltaTime = 1.0;
  20961. Scene.MaxDeltaTime = 1000.0;
  20962. /** The distance in pixel that you have to move to prevent some events */
  20963. Scene.DragMovementThreshold = 10; // in pixels
  20964. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20965. Scene.LongPressDelay = 500; // in milliseconds
  20966. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20967. Scene.DoubleClickDelay = 300; // in milliseconds
  20968. /** If you need to check double click without raising a single click at first click, enable this flag */
  20969. Scene.ExclusiveDoubleClickMode = false;
  20970. return Scene;
  20971. }());
  20972. BABYLON.Scene = Scene;
  20973. })(BABYLON || (BABYLON = {}));
  20974. //# sourceMappingURL=babylon.scene.js.map
  20975. var BABYLON;
  20976. (function (BABYLON) {
  20977. var Buffer = /** @class */ (function () {
  20978. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20979. if (instanced === void 0) { instanced = false; }
  20980. if (engine instanceof BABYLON.Mesh) {
  20981. this._engine = engine.getScene().getEngine();
  20982. }
  20983. else {
  20984. this._engine = engine;
  20985. }
  20986. this._updatable = updatable;
  20987. this._data = data;
  20988. this._strideSize = stride;
  20989. if (!postponeInternalCreation) {
  20990. this.create();
  20991. }
  20992. this._instanced = instanced;
  20993. this._instanceDivisor = instanced ? 1 : 0;
  20994. }
  20995. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20996. // a lot of these parameters are ignored as they are overriden by the buffer
  20997. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20998. };
  20999. // Properties
  21000. Buffer.prototype.isUpdatable = function () {
  21001. return this._updatable;
  21002. };
  21003. Buffer.prototype.getData = function () {
  21004. return this._data;
  21005. };
  21006. Buffer.prototype.getBuffer = function () {
  21007. return this._buffer;
  21008. };
  21009. Buffer.prototype.getStrideSize = function () {
  21010. return this._strideSize;
  21011. };
  21012. Buffer.prototype.getIsInstanced = function () {
  21013. return this._instanced;
  21014. };
  21015. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21016. get: function () {
  21017. return this._instanceDivisor;
  21018. },
  21019. set: function (value) {
  21020. this._instanceDivisor = value;
  21021. if (value == 0) {
  21022. this._instanced = false;
  21023. }
  21024. else {
  21025. this._instanced = true;
  21026. }
  21027. },
  21028. enumerable: true,
  21029. configurable: true
  21030. });
  21031. // Methods
  21032. Buffer.prototype.create = function (data) {
  21033. if (data === void 0) { data = null; }
  21034. if (!data && this._buffer) {
  21035. return; // nothing to do
  21036. }
  21037. data = data || this._data;
  21038. if (!data) {
  21039. return;
  21040. }
  21041. if (!this._buffer) {
  21042. if (this._updatable) {
  21043. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21044. this._data = data;
  21045. }
  21046. else {
  21047. this._buffer = this._engine.createVertexBuffer(data);
  21048. }
  21049. }
  21050. else if (this._updatable) {
  21051. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21052. this._data = data;
  21053. }
  21054. };
  21055. Buffer.prototype._rebuild = function () {
  21056. this._buffer = null;
  21057. this.create(this._data);
  21058. };
  21059. Buffer.prototype.update = function (data) {
  21060. this.create(data);
  21061. };
  21062. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21063. if (!this._buffer) {
  21064. return;
  21065. }
  21066. if (this._updatable) {
  21067. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21068. this._data = null;
  21069. }
  21070. };
  21071. Buffer.prototype.dispose = function () {
  21072. if (!this._buffer) {
  21073. return;
  21074. }
  21075. if (this._engine._releaseBuffer(this._buffer)) {
  21076. this._buffer = null;
  21077. }
  21078. };
  21079. return Buffer;
  21080. }());
  21081. BABYLON.Buffer = Buffer;
  21082. })(BABYLON || (BABYLON = {}));
  21083. //# sourceMappingURL=babylon.buffer.js.map
  21084. var BABYLON;
  21085. (function (BABYLON) {
  21086. var VertexBuffer = /** @class */ (function () {
  21087. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21088. if (!stride) {
  21089. // Deduce stride from kind
  21090. switch (kind) {
  21091. case VertexBuffer.PositionKind:
  21092. stride = 3;
  21093. break;
  21094. case VertexBuffer.NormalKind:
  21095. stride = 3;
  21096. break;
  21097. case VertexBuffer.UVKind:
  21098. case VertexBuffer.UV2Kind:
  21099. case VertexBuffer.UV3Kind:
  21100. case VertexBuffer.UV4Kind:
  21101. case VertexBuffer.UV5Kind:
  21102. case VertexBuffer.UV6Kind:
  21103. stride = 2;
  21104. break;
  21105. case VertexBuffer.TangentKind:
  21106. case VertexBuffer.ColorKind:
  21107. stride = 4;
  21108. break;
  21109. case VertexBuffer.MatricesIndicesKind:
  21110. case VertexBuffer.MatricesIndicesExtraKind:
  21111. stride = 4;
  21112. break;
  21113. case VertexBuffer.MatricesWeightsKind:
  21114. case VertexBuffer.MatricesWeightsExtraKind:
  21115. default:
  21116. stride = 4;
  21117. break;
  21118. }
  21119. }
  21120. if (data instanceof BABYLON.Buffer) {
  21121. if (!stride) {
  21122. stride = data.getStrideSize();
  21123. }
  21124. this._buffer = data;
  21125. this._ownsBuffer = false;
  21126. }
  21127. else {
  21128. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21129. this._ownsBuffer = true;
  21130. }
  21131. this._stride = stride;
  21132. this._offset = offset ? offset : 0;
  21133. this._size = size ? size : stride;
  21134. this._kind = kind;
  21135. }
  21136. VertexBuffer.prototype._rebuild = function () {
  21137. if (!this._buffer) {
  21138. return;
  21139. }
  21140. this._buffer._rebuild();
  21141. };
  21142. /**
  21143. * Returns the kind of the VertexBuffer (string).
  21144. */
  21145. VertexBuffer.prototype.getKind = function () {
  21146. return this._kind;
  21147. };
  21148. // Properties
  21149. /**
  21150. * Boolean : is the VertexBuffer updatable ?
  21151. */
  21152. VertexBuffer.prototype.isUpdatable = function () {
  21153. return this._buffer.isUpdatable();
  21154. };
  21155. /**
  21156. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21157. */
  21158. VertexBuffer.prototype.getData = function () {
  21159. return this._buffer.getData();
  21160. };
  21161. /**
  21162. * Returns the WebGLBuffer associated to the VertexBuffer.
  21163. */
  21164. VertexBuffer.prototype.getBuffer = function () {
  21165. return this._buffer.getBuffer();
  21166. };
  21167. /**
  21168. * Returns the stride of the VertexBuffer (integer).
  21169. */
  21170. VertexBuffer.prototype.getStrideSize = function () {
  21171. return this._stride;
  21172. };
  21173. /**
  21174. * Returns the offset (integer).
  21175. */
  21176. VertexBuffer.prototype.getOffset = function () {
  21177. return this._offset;
  21178. };
  21179. /**
  21180. * Returns the VertexBuffer total size (integer).
  21181. */
  21182. VertexBuffer.prototype.getSize = function () {
  21183. return this._size;
  21184. };
  21185. /**
  21186. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21187. */
  21188. VertexBuffer.prototype.getIsInstanced = function () {
  21189. return this._buffer.getIsInstanced();
  21190. };
  21191. /**
  21192. * Returns the instancing divisor, zero for non-instanced (integer).
  21193. */
  21194. VertexBuffer.prototype.getInstanceDivisor = function () {
  21195. return this._buffer.instanceDivisor;
  21196. };
  21197. // Methods
  21198. /**
  21199. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21200. * Returns the created WebGLBuffer.
  21201. */
  21202. VertexBuffer.prototype.create = function (data) {
  21203. return this._buffer.create(data);
  21204. };
  21205. /**
  21206. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21207. * Returns the updated WebGLBuffer.
  21208. */
  21209. VertexBuffer.prototype.update = function (data) {
  21210. return this._buffer.update(data);
  21211. };
  21212. /**
  21213. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21214. * Returns the directly updated WebGLBuffer.
  21215. */
  21216. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21217. return this._buffer.updateDirectly(data, offset);
  21218. };
  21219. /**
  21220. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21221. */
  21222. VertexBuffer.prototype.dispose = function () {
  21223. if (this._ownsBuffer) {
  21224. this._buffer.dispose();
  21225. }
  21226. };
  21227. Object.defineProperty(VertexBuffer, "PositionKind", {
  21228. get: function () {
  21229. return VertexBuffer._PositionKind;
  21230. },
  21231. enumerable: true,
  21232. configurable: true
  21233. });
  21234. Object.defineProperty(VertexBuffer, "NormalKind", {
  21235. get: function () {
  21236. return VertexBuffer._NormalKind;
  21237. },
  21238. enumerable: true,
  21239. configurable: true
  21240. });
  21241. Object.defineProperty(VertexBuffer, "TangentKind", {
  21242. get: function () {
  21243. return VertexBuffer._TangentKind;
  21244. },
  21245. enumerable: true,
  21246. configurable: true
  21247. });
  21248. Object.defineProperty(VertexBuffer, "UVKind", {
  21249. get: function () {
  21250. return VertexBuffer._UVKind;
  21251. },
  21252. enumerable: true,
  21253. configurable: true
  21254. });
  21255. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21256. get: function () {
  21257. return VertexBuffer._UV2Kind;
  21258. },
  21259. enumerable: true,
  21260. configurable: true
  21261. });
  21262. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21263. get: function () {
  21264. return VertexBuffer._UV3Kind;
  21265. },
  21266. enumerable: true,
  21267. configurable: true
  21268. });
  21269. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21270. get: function () {
  21271. return VertexBuffer._UV4Kind;
  21272. },
  21273. enumerable: true,
  21274. configurable: true
  21275. });
  21276. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21277. get: function () {
  21278. return VertexBuffer._UV5Kind;
  21279. },
  21280. enumerable: true,
  21281. configurable: true
  21282. });
  21283. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21284. get: function () {
  21285. return VertexBuffer._UV6Kind;
  21286. },
  21287. enumerable: true,
  21288. configurable: true
  21289. });
  21290. Object.defineProperty(VertexBuffer, "ColorKind", {
  21291. get: function () {
  21292. return VertexBuffer._ColorKind;
  21293. },
  21294. enumerable: true,
  21295. configurable: true
  21296. });
  21297. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21298. get: function () {
  21299. return VertexBuffer._MatricesIndicesKind;
  21300. },
  21301. enumerable: true,
  21302. configurable: true
  21303. });
  21304. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21305. get: function () {
  21306. return VertexBuffer._MatricesWeightsKind;
  21307. },
  21308. enumerable: true,
  21309. configurable: true
  21310. });
  21311. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21312. get: function () {
  21313. return VertexBuffer._MatricesIndicesExtraKind;
  21314. },
  21315. enumerable: true,
  21316. configurable: true
  21317. });
  21318. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21319. get: function () {
  21320. return VertexBuffer._MatricesWeightsExtraKind;
  21321. },
  21322. enumerable: true,
  21323. configurable: true
  21324. });
  21325. // Enums
  21326. VertexBuffer._PositionKind = "position";
  21327. VertexBuffer._NormalKind = "normal";
  21328. VertexBuffer._TangentKind = "tangent";
  21329. VertexBuffer._UVKind = "uv";
  21330. VertexBuffer._UV2Kind = "uv2";
  21331. VertexBuffer._UV3Kind = "uv3";
  21332. VertexBuffer._UV4Kind = "uv4";
  21333. VertexBuffer._UV5Kind = "uv5";
  21334. VertexBuffer._UV6Kind = "uv6";
  21335. VertexBuffer._ColorKind = "color";
  21336. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21337. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21338. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21339. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21340. return VertexBuffer;
  21341. }());
  21342. BABYLON.VertexBuffer = VertexBuffer;
  21343. })(BABYLON || (BABYLON = {}));
  21344. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21345. var BABYLON;
  21346. (function (BABYLON) {
  21347. var InternalTexture = /** @class */ (function () {
  21348. function InternalTexture(engine, dataSource) {
  21349. this.onLoadedObservable = new BABYLON.Observable();
  21350. // Private
  21351. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21352. this._references = 1;
  21353. this._engine = engine;
  21354. this._dataSource = dataSource;
  21355. this._webGLTexture = engine._createTexture();
  21356. }
  21357. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21358. get: function () {
  21359. return this._dataSource;
  21360. },
  21361. enumerable: true,
  21362. configurable: true
  21363. });
  21364. InternalTexture.prototype.incrementReferences = function () {
  21365. this._references++;
  21366. };
  21367. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21368. if (depth === void 0) { depth = 1; }
  21369. this.width = width;
  21370. this.height = height;
  21371. this.depth = depth;
  21372. this.baseWidth = width;
  21373. this.baseHeight = height;
  21374. this.baseDepth = depth;
  21375. this._size = width * height * depth;
  21376. };
  21377. InternalTexture.prototype._rebuild = function () {
  21378. var _this = this;
  21379. var proxy;
  21380. this.isReady = false;
  21381. this._cachedCoordinatesMode = null;
  21382. this._cachedWrapU = null;
  21383. this._cachedWrapV = null;
  21384. this._cachedAnisotropicFilteringLevel = null;
  21385. switch (this._dataSource) {
  21386. case InternalTexture.DATASOURCE_TEMP:
  21387. return;
  21388. case InternalTexture.DATASOURCE_URL:
  21389. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21390. _this.isReady = true;
  21391. }, null, this._buffer, undefined, this.format);
  21392. proxy._swapAndDie(this);
  21393. return;
  21394. case InternalTexture.DATASOURCE_RAW:
  21395. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21396. proxy._swapAndDie(this);
  21397. this.isReady = true;
  21398. return;
  21399. case InternalTexture.DATASOURCE_RAW3D:
  21400. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21401. proxy._swapAndDie(this);
  21402. this.isReady = true;
  21403. return;
  21404. case InternalTexture.DATASOURCE_DYNAMIC:
  21405. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21406. proxy._swapAndDie(this);
  21407. // The engine will make sure to update content so no need to flag it as isReady = true
  21408. return;
  21409. case InternalTexture.DATASOURCE_RENDERTARGET:
  21410. var options = new BABYLON.RenderTargetCreationOptions();
  21411. options.generateDepthBuffer = this._generateDepthBuffer;
  21412. options.generateMipMaps = this.generateMipMaps;
  21413. options.generateStencilBuffer = this._generateStencilBuffer;
  21414. options.samplingMode = this.samplingMode;
  21415. options.type = this.type;
  21416. if (this.isCube) {
  21417. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21418. }
  21419. else {
  21420. var size = {
  21421. width: this.width,
  21422. height: this.height
  21423. };
  21424. proxy = this._engine.createRenderTargetTexture(size, options);
  21425. }
  21426. proxy._swapAndDie(this);
  21427. this.isReady = true;
  21428. return;
  21429. case InternalTexture.DATASOURCE_CUBE:
  21430. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21431. _this.isReady = true;
  21432. }, null, this.format, this._extension);
  21433. proxy._swapAndDie(this);
  21434. return;
  21435. case InternalTexture.DATASOURCE_CUBERAW:
  21436. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21437. proxy._swapAndDie(this);
  21438. this.isReady = true;
  21439. return;
  21440. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21441. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21442. if (proxy) {
  21443. proxy._swapAndDie(_this);
  21444. }
  21445. _this.isReady = true;
  21446. }, null, this.format, this._extension);
  21447. return;
  21448. }
  21449. };
  21450. InternalTexture.prototype._swapAndDie = function (target) {
  21451. target._webGLTexture = this._webGLTexture;
  21452. if (this._framebuffer) {
  21453. target._framebuffer = this._framebuffer;
  21454. }
  21455. if (this._depthStencilBuffer) {
  21456. target._depthStencilBuffer = this._depthStencilBuffer;
  21457. }
  21458. if (this._lodTextureHigh) {
  21459. if (target._lodTextureHigh) {
  21460. target._lodTextureHigh.dispose();
  21461. }
  21462. target._lodTextureHigh = this._lodTextureHigh;
  21463. }
  21464. if (this._lodTextureMid) {
  21465. if (target._lodTextureMid) {
  21466. target._lodTextureMid.dispose();
  21467. }
  21468. target._lodTextureMid = this._lodTextureMid;
  21469. }
  21470. if (this._lodTextureLow) {
  21471. if (target._lodTextureLow) {
  21472. target._lodTextureLow.dispose();
  21473. }
  21474. target._lodTextureLow = this._lodTextureLow;
  21475. }
  21476. var cache = this._engine.getLoadedTexturesCache();
  21477. var index = cache.indexOf(this);
  21478. if (index !== -1) {
  21479. cache.splice(index, 1);
  21480. }
  21481. };
  21482. InternalTexture.prototype.dispose = function () {
  21483. if (!this._webGLTexture) {
  21484. return;
  21485. }
  21486. this._references--;
  21487. if (this._references === 0) {
  21488. this._engine._releaseTexture(this);
  21489. this._webGLTexture = null;
  21490. }
  21491. };
  21492. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21493. InternalTexture.DATASOURCE_URL = 1;
  21494. InternalTexture.DATASOURCE_TEMP = 2;
  21495. InternalTexture.DATASOURCE_RAW = 3;
  21496. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21497. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21498. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21499. InternalTexture.DATASOURCE_CUBE = 7;
  21500. InternalTexture.DATASOURCE_CUBERAW = 8;
  21501. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21502. InternalTexture.DATASOURCE_RAW3D = 10;
  21503. return InternalTexture;
  21504. }());
  21505. BABYLON.InternalTexture = InternalTexture;
  21506. })(BABYLON || (BABYLON = {}));
  21507. //# sourceMappingURL=babylon.internalTexture.js.map
  21508. var BABYLON;
  21509. (function (BABYLON) {
  21510. var BaseTexture = /** @class */ (function () {
  21511. function BaseTexture(scene) {
  21512. this._hasAlpha = false;
  21513. this.getAlphaFromRGB = false;
  21514. this.level = 1;
  21515. this.coordinatesIndex = 0;
  21516. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21517. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21518. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21519. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  21520. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  21521. this.isCube = false;
  21522. this.is3D = false;
  21523. this.gammaSpace = true;
  21524. this.invertZ = false;
  21525. this.lodLevelInAlpha = false;
  21526. this.lodGenerationOffset = 0.0;
  21527. this.lodGenerationScale = 0.8;
  21528. this.isRenderTarget = false;
  21529. this.animations = new Array();
  21530. /**
  21531. * An event triggered when the texture is disposed.
  21532. * @type {BABYLON.Observable}
  21533. */
  21534. this.onDisposeObservable = new BABYLON.Observable();
  21535. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21536. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  21537. if (this._scene) {
  21538. this._scene.textures.push(this);
  21539. }
  21540. this._uid = null;
  21541. }
  21542. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  21543. get: function () {
  21544. return this._hasAlpha;
  21545. },
  21546. set: function (value) {
  21547. if (this._hasAlpha === value) {
  21548. return;
  21549. }
  21550. this._hasAlpha = value;
  21551. if (this._scene) {
  21552. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21553. }
  21554. },
  21555. enumerable: true,
  21556. configurable: true
  21557. });
  21558. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  21559. get: function () {
  21560. return this._coordinatesMode;
  21561. },
  21562. set: function (value) {
  21563. if (this._coordinatesMode === value) {
  21564. return;
  21565. }
  21566. this._coordinatesMode = value;
  21567. if (this._scene) {
  21568. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21569. }
  21570. },
  21571. enumerable: true,
  21572. configurable: true
  21573. });
  21574. Object.defineProperty(BaseTexture.prototype, "uid", {
  21575. get: function () {
  21576. if (!this._uid) {
  21577. this._uid = BABYLON.Tools.RandomId();
  21578. }
  21579. return this._uid;
  21580. },
  21581. enumerable: true,
  21582. configurable: true
  21583. });
  21584. BaseTexture.prototype.toString = function () {
  21585. return this.name;
  21586. };
  21587. BaseTexture.prototype.getClassName = function () {
  21588. return "BaseTexture";
  21589. };
  21590. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21591. set: function (callback) {
  21592. if (this._onDisposeObserver) {
  21593. this.onDisposeObservable.remove(this._onDisposeObserver);
  21594. }
  21595. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21596. },
  21597. enumerable: true,
  21598. configurable: true
  21599. });
  21600. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  21601. get: function () {
  21602. return true;
  21603. },
  21604. enumerable: true,
  21605. configurable: true
  21606. });
  21607. BaseTexture.prototype.getScene = function () {
  21608. return this._scene;
  21609. };
  21610. BaseTexture.prototype.getTextureMatrix = function () {
  21611. return BABYLON.Matrix.IdentityReadOnly;
  21612. };
  21613. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21614. return BABYLON.Matrix.IdentityReadOnly;
  21615. };
  21616. BaseTexture.prototype.getInternalTexture = function () {
  21617. return this._texture;
  21618. };
  21619. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  21620. return !this.isBlocking || this.isReady();
  21621. };
  21622. BaseTexture.prototype.isReady = function () {
  21623. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21624. this.delayLoad();
  21625. return false;
  21626. }
  21627. if (this._texture) {
  21628. return this._texture.isReady;
  21629. }
  21630. return false;
  21631. };
  21632. BaseTexture.prototype.getSize = function () {
  21633. if (this._texture && this._texture.width) {
  21634. return new BABYLON.Size(this._texture.width, this._texture.height);
  21635. }
  21636. if (this._texture && this._texture._size) {
  21637. return new BABYLON.Size(this._texture._size, this._texture._size);
  21638. }
  21639. return BABYLON.Size.Zero();
  21640. };
  21641. BaseTexture.prototype.getBaseSize = function () {
  21642. if (!this.isReady() || !this._texture)
  21643. return BABYLON.Size.Zero();
  21644. if (this._texture._size) {
  21645. return new BABYLON.Size(this._texture._size, this._texture._size);
  21646. }
  21647. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  21648. };
  21649. BaseTexture.prototype.scale = function (ratio) {
  21650. };
  21651. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21652. get: function () {
  21653. return false;
  21654. },
  21655. enumerable: true,
  21656. configurable: true
  21657. });
  21658. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21659. if (!this._scene) {
  21660. return null;
  21661. }
  21662. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21663. for (var index = 0; index < texturesCache.length; index++) {
  21664. var texturesCacheEntry = texturesCache[index];
  21665. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  21666. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21667. texturesCacheEntry.incrementReferences();
  21668. return texturesCacheEntry;
  21669. }
  21670. }
  21671. }
  21672. return null;
  21673. };
  21674. BaseTexture.prototype._rebuild = function () {
  21675. };
  21676. BaseTexture.prototype.delayLoad = function () {
  21677. };
  21678. BaseTexture.prototype.clone = function () {
  21679. return null;
  21680. };
  21681. Object.defineProperty(BaseTexture.prototype, "textureType", {
  21682. get: function () {
  21683. if (!this._texture) {
  21684. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21685. }
  21686. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21687. },
  21688. enumerable: true,
  21689. configurable: true
  21690. });
  21691. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  21692. get: function () {
  21693. if (!this._texture) {
  21694. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21695. }
  21696. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21697. },
  21698. enumerable: true,
  21699. configurable: true
  21700. });
  21701. BaseTexture.prototype.readPixels = function (faceIndex) {
  21702. if (faceIndex === void 0) { faceIndex = 0; }
  21703. if (!this._texture) {
  21704. return null;
  21705. }
  21706. var size = this.getSize();
  21707. var scene = this.getScene();
  21708. if (!scene) {
  21709. return null;
  21710. }
  21711. var engine = scene.getEngine();
  21712. if (this._texture.isCube) {
  21713. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  21714. }
  21715. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  21716. };
  21717. BaseTexture.prototype.releaseInternalTexture = function () {
  21718. if (this._texture) {
  21719. this._texture.dispose();
  21720. this._texture = null;
  21721. }
  21722. };
  21723. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  21724. get: function () {
  21725. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  21726. return null;
  21727. }
  21728. if (!this._texture._sphericalPolynomial) {
  21729. this._texture._sphericalPolynomial =
  21730. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  21731. }
  21732. return this._texture._sphericalPolynomial;
  21733. },
  21734. set: function (value) {
  21735. if (this._texture) {
  21736. this._texture._sphericalPolynomial = value;
  21737. }
  21738. },
  21739. enumerable: true,
  21740. configurable: true
  21741. });
  21742. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21743. get: function () {
  21744. if (this._texture) {
  21745. return this._texture._lodTextureHigh;
  21746. }
  21747. return null;
  21748. },
  21749. enumerable: true,
  21750. configurable: true
  21751. });
  21752. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21753. get: function () {
  21754. if (this._texture) {
  21755. return this._texture._lodTextureMid;
  21756. }
  21757. return null;
  21758. },
  21759. enumerable: true,
  21760. configurable: true
  21761. });
  21762. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21763. get: function () {
  21764. if (this._texture) {
  21765. return this._texture._lodTextureLow;
  21766. }
  21767. return null;
  21768. },
  21769. enumerable: true,
  21770. configurable: true
  21771. });
  21772. BaseTexture.prototype.dispose = function () {
  21773. if (!this._scene) {
  21774. return;
  21775. }
  21776. // Animations
  21777. this._scene.stopAnimation(this);
  21778. // Remove from scene
  21779. this._scene._removePendingData(this);
  21780. var index = this._scene.textures.indexOf(this);
  21781. if (index >= 0) {
  21782. this._scene.textures.splice(index, 1);
  21783. }
  21784. if (this._texture === undefined) {
  21785. return;
  21786. }
  21787. // Release
  21788. this.releaseInternalTexture();
  21789. // Callback
  21790. this.onDisposeObservable.notifyObservers(this);
  21791. this.onDisposeObservable.clear();
  21792. };
  21793. BaseTexture.prototype.serialize = function () {
  21794. if (!this.name) {
  21795. return null;
  21796. }
  21797. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21798. // Animations
  21799. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21800. return serializationObject;
  21801. };
  21802. BaseTexture.WhenAllReady = function (textures, callback) {
  21803. var numRemaining = textures.length;
  21804. if (numRemaining === 0) {
  21805. callback();
  21806. return;
  21807. }
  21808. var _loop_1 = function () {
  21809. texture = textures[i];
  21810. if (texture.isReady()) {
  21811. if (--numRemaining === 0) {
  21812. callback();
  21813. }
  21814. }
  21815. else {
  21816. onLoadObservable = texture.onLoadObservable;
  21817. var onLoadCallback_1 = function () {
  21818. onLoadObservable.removeCallback(onLoadCallback_1);
  21819. if (--numRemaining === 0) {
  21820. callback();
  21821. }
  21822. };
  21823. onLoadObservable.add(onLoadCallback_1);
  21824. }
  21825. };
  21826. var texture, onLoadObservable;
  21827. for (var i = 0; i < textures.length; i++) {
  21828. _loop_1();
  21829. }
  21830. };
  21831. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  21832. __decorate([
  21833. BABYLON.serialize()
  21834. ], BaseTexture.prototype, "name", void 0);
  21835. __decorate([
  21836. BABYLON.serialize("hasAlpha")
  21837. ], BaseTexture.prototype, "_hasAlpha", void 0);
  21838. __decorate([
  21839. BABYLON.serialize()
  21840. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21841. __decorate([
  21842. BABYLON.serialize()
  21843. ], BaseTexture.prototype, "level", void 0);
  21844. __decorate([
  21845. BABYLON.serialize()
  21846. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21847. __decorate([
  21848. BABYLON.serialize("coordinatesMode")
  21849. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21850. __decorate([
  21851. BABYLON.serialize()
  21852. ], BaseTexture.prototype, "wrapU", void 0);
  21853. __decorate([
  21854. BABYLON.serialize()
  21855. ], BaseTexture.prototype, "wrapV", void 0);
  21856. __decorate([
  21857. BABYLON.serialize()
  21858. ], BaseTexture.prototype, "wrapR", void 0);
  21859. __decorate([
  21860. BABYLON.serialize()
  21861. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21862. __decorate([
  21863. BABYLON.serialize()
  21864. ], BaseTexture.prototype, "isCube", void 0);
  21865. __decorate([
  21866. BABYLON.serialize()
  21867. ], BaseTexture.prototype, "is3D", void 0);
  21868. __decorate([
  21869. BABYLON.serialize()
  21870. ], BaseTexture.prototype, "gammaSpace", void 0);
  21871. __decorate([
  21872. BABYLON.serialize()
  21873. ], BaseTexture.prototype, "invertZ", void 0);
  21874. __decorate([
  21875. BABYLON.serialize()
  21876. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21877. __decorate([
  21878. BABYLON.serialize()
  21879. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21880. __decorate([
  21881. BABYLON.serialize()
  21882. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21883. __decorate([
  21884. BABYLON.serialize()
  21885. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21886. return BaseTexture;
  21887. }());
  21888. BABYLON.BaseTexture = BaseTexture;
  21889. })(BABYLON || (BABYLON = {}));
  21890. //# sourceMappingURL=babylon.baseTexture.js.map
  21891. var BABYLON;
  21892. (function (BABYLON) {
  21893. var Texture = /** @class */ (function (_super) {
  21894. __extends(Texture, _super);
  21895. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21896. if (noMipmap === void 0) { noMipmap = false; }
  21897. if (invertY === void 0) { invertY = true; }
  21898. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21899. if (onLoad === void 0) { onLoad = null; }
  21900. if (onError === void 0) { onError = null; }
  21901. if (buffer === void 0) { buffer = null; }
  21902. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21903. var _this = _super.call(this, scene) || this;
  21904. _this.uOffset = 0;
  21905. _this.vOffset = 0;
  21906. _this.uScale = 1.0;
  21907. _this.vScale = 1.0;
  21908. _this.uAng = 0;
  21909. _this.vAng = 0;
  21910. _this.wAng = 0;
  21911. _this._isBlocking = true;
  21912. _this.name = url || "";
  21913. _this.url = url;
  21914. _this._noMipmap = noMipmap;
  21915. _this._invertY = invertY;
  21916. _this._samplingMode = samplingMode;
  21917. _this._buffer = buffer;
  21918. _this._deleteBuffer = deleteBuffer;
  21919. if (format) {
  21920. _this._format = format;
  21921. }
  21922. scene = _this.getScene();
  21923. if (!scene) {
  21924. return _this;
  21925. }
  21926. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21927. var load = function () {
  21928. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21929. _this.onLoadObservable.notifyObservers(_this);
  21930. }
  21931. if (onLoad) {
  21932. onLoad();
  21933. }
  21934. if (!_this.isBlocking && scene) {
  21935. scene.resetCachedMaterial();
  21936. }
  21937. };
  21938. if (!_this.url) {
  21939. _this._delayedOnLoad = load;
  21940. _this._delayedOnError = onError;
  21941. return _this;
  21942. }
  21943. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21944. if (!_this._texture) {
  21945. if (!scene.useDelayedTextureLoading) {
  21946. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  21947. if (deleteBuffer) {
  21948. delete _this._buffer;
  21949. }
  21950. }
  21951. else {
  21952. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21953. _this._delayedOnLoad = load;
  21954. _this._delayedOnError = onError;
  21955. }
  21956. }
  21957. else {
  21958. if (_this._texture.isReady) {
  21959. BABYLON.Tools.SetImmediate(function () { return load(); });
  21960. }
  21961. else {
  21962. _this._texture.onLoadedObservable.add(load);
  21963. }
  21964. }
  21965. return _this;
  21966. }
  21967. Object.defineProperty(Texture.prototype, "noMipmap", {
  21968. get: function () {
  21969. return this._noMipmap;
  21970. },
  21971. enumerable: true,
  21972. configurable: true
  21973. });
  21974. Object.defineProperty(Texture.prototype, "isBlocking", {
  21975. get: function () {
  21976. return this._isBlocking;
  21977. },
  21978. set: function (value) {
  21979. this._isBlocking = value;
  21980. },
  21981. enumerable: true,
  21982. configurable: true
  21983. });
  21984. Object.defineProperty(Texture.prototype, "samplingMode", {
  21985. get: function () {
  21986. return this._samplingMode;
  21987. },
  21988. enumerable: true,
  21989. configurable: true
  21990. });
  21991. Texture.prototype.updateURL = function (url) {
  21992. this.url = url;
  21993. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21994. this.delayLoad();
  21995. };
  21996. Texture.prototype.delayLoad = function () {
  21997. var _this = this;
  21998. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21999. return;
  22000. }
  22001. var scene = this.getScene();
  22002. if (!scene) {
  22003. return;
  22004. }
  22005. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22006. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22007. if (!this._texture) {
  22008. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22009. if (this._deleteBuffer) {
  22010. delete this._buffer;
  22011. }
  22012. }
  22013. else {
  22014. if (this._texture.isReady) {
  22015. BABYLON.Tools.SetImmediate(function () {
  22016. if (!_this._delayedOnLoad) {
  22017. return;
  22018. }
  22019. _this._delayedOnLoad();
  22020. });
  22021. }
  22022. else {
  22023. if (this._delayedOnLoad) {
  22024. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22025. }
  22026. }
  22027. }
  22028. };
  22029. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22030. if (!this._texture) {
  22031. return;
  22032. }
  22033. var scene = this.getScene();
  22034. if (!scene) {
  22035. return;
  22036. }
  22037. this._samplingMode = samplingMode;
  22038. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22039. };
  22040. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22041. x *= this.uScale;
  22042. y *= this.vScale;
  22043. x -= 0.5 * this.uScale;
  22044. y -= 0.5 * this.vScale;
  22045. z -= 0.5;
  22046. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22047. t.x += 0.5 * this.uScale + this.uOffset;
  22048. t.y += 0.5 * this.vScale + this.vOffset;
  22049. t.z += 0.5;
  22050. };
  22051. Texture.prototype.getTextureMatrix = function () {
  22052. var _this = this;
  22053. if (this.uOffset === this._cachedUOffset &&
  22054. this.vOffset === this._cachedVOffset &&
  22055. this.uScale === this._cachedUScale &&
  22056. this.vScale === this._cachedVScale &&
  22057. this.uAng === this._cachedUAng &&
  22058. this.vAng === this._cachedVAng &&
  22059. this.wAng === this._cachedWAng) {
  22060. return this._cachedTextureMatrix;
  22061. }
  22062. this._cachedUOffset = this.uOffset;
  22063. this._cachedVOffset = this.vOffset;
  22064. this._cachedUScale = this.uScale;
  22065. this._cachedVScale = this.vScale;
  22066. this._cachedUAng = this.uAng;
  22067. this._cachedVAng = this.vAng;
  22068. this._cachedWAng = this.wAng;
  22069. if (!this._cachedTextureMatrix) {
  22070. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22071. this._rowGenerationMatrix = new BABYLON.Matrix();
  22072. this._t0 = BABYLON.Vector3.Zero();
  22073. this._t1 = BABYLON.Vector3.Zero();
  22074. this._t2 = BABYLON.Vector3.Zero();
  22075. }
  22076. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22077. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22078. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22079. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22080. this._t1.subtractInPlace(this._t0);
  22081. this._t2.subtractInPlace(this._t0);
  22082. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22083. this._cachedTextureMatrix.m[0] = this._t1.x;
  22084. this._cachedTextureMatrix.m[1] = this._t1.y;
  22085. this._cachedTextureMatrix.m[2] = this._t1.z;
  22086. this._cachedTextureMatrix.m[4] = this._t2.x;
  22087. this._cachedTextureMatrix.m[5] = this._t2.y;
  22088. this._cachedTextureMatrix.m[6] = this._t2.z;
  22089. this._cachedTextureMatrix.m[8] = this._t0.x;
  22090. this._cachedTextureMatrix.m[9] = this._t0.y;
  22091. this._cachedTextureMatrix.m[10] = this._t0.z;
  22092. var scene = this.getScene();
  22093. if (!scene) {
  22094. return this._cachedTextureMatrix;
  22095. }
  22096. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22097. return mat.hasTexture(_this);
  22098. });
  22099. return this._cachedTextureMatrix;
  22100. };
  22101. Texture.prototype.getReflectionTextureMatrix = function () {
  22102. var _this = this;
  22103. var scene = this.getScene();
  22104. if (!scene) {
  22105. return this._cachedTextureMatrix;
  22106. }
  22107. if (this.uOffset === this._cachedUOffset &&
  22108. this.vOffset === this._cachedVOffset &&
  22109. this.uScale === this._cachedUScale &&
  22110. this.vScale === this._cachedVScale &&
  22111. this.coordinatesMode === this._cachedCoordinatesMode) {
  22112. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22113. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22114. return this._cachedTextureMatrix;
  22115. }
  22116. }
  22117. else {
  22118. return this._cachedTextureMatrix;
  22119. }
  22120. }
  22121. if (!this._cachedTextureMatrix) {
  22122. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22123. }
  22124. if (!this._projectionModeMatrix) {
  22125. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22126. }
  22127. this._cachedUOffset = this.uOffset;
  22128. this._cachedVOffset = this.vOffset;
  22129. this._cachedUScale = this.uScale;
  22130. this._cachedVScale = this.vScale;
  22131. this._cachedCoordinatesMode = this.coordinatesMode;
  22132. switch (this.coordinatesMode) {
  22133. case Texture.PLANAR_MODE:
  22134. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22135. this._cachedTextureMatrix[0] = this.uScale;
  22136. this._cachedTextureMatrix[5] = this.vScale;
  22137. this._cachedTextureMatrix[12] = this.uOffset;
  22138. this._cachedTextureMatrix[13] = this.vOffset;
  22139. break;
  22140. case Texture.PROJECTION_MODE:
  22141. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22142. this._projectionModeMatrix.m[0] = 0.5;
  22143. this._projectionModeMatrix.m[5] = -0.5;
  22144. this._projectionModeMatrix.m[10] = 0.0;
  22145. this._projectionModeMatrix.m[12] = 0.5;
  22146. this._projectionModeMatrix.m[13] = 0.5;
  22147. this._projectionModeMatrix.m[14] = 1.0;
  22148. this._projectionModeMatrix.m[15] = 1.0;
  22149. var projectionMatrix = scene.getProjectionMatrix();
  22150. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22151. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22152. break;
  22153. default:
  22154. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22155. break;
  22156. }
  22157. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22158. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22159. });
  22160. return this._cachedTextureMatrix;
  22161. };
  22162. Texture.prototype.clone = function () {
  22163. var _this = this;
  22164. return BABYLON.SerializationHelper.Clone(function () {
  22165. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22166. }, this);
  22167. };
  22168. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22169. get: function () {
  22170. if (!this._onLoadObservable) {
  22171. this._onLoadObservable = new BABYLON.Observable();
  22172. }
  22173. return this._onLoadObservable;
  22174. },
  22175. enumerable: true,
  22176. configurable: true
  22177. });
  22178. Texture.prototype.serialize = function () {
  22179. var serializationObject = _super.prototype.serialize.call(this);
  22180. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22181. serializationObject.base64String = this._buffer;
  22182. serializationObject.name = serializationObject.name.replace("data:", "");
  22183. }
  22184. return serializationObject;
  22185. };
  22186. Texture.prototype.getClassName = function () {
  22187. return "Texture";
  22188. };
  22189. Texture.prototype.dispose = function () {
  22190. _super.prototype.dispose.call(this);
  22191. if (this.onLoadObservable) {
  22192. this.onLoadObservable.clear();
  22193. this._onLoadObservable = null;
  22194. }
  22195. this._delayedOnLoad = null;
  22196. this._delayedOnError = null;
  22197. };
  22198. // Statics
  22199. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22200. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22201. if (onLoad === void 0) { onLoad = null; }
  22202. if (onError === void 0) { onError = null; }
  22203. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22204. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22205. };
  22206. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22207. if (parsedTexture.customType) {
  22208. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22209. // Update Sampling Mode
  22210. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22211. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22212. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22213. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22214. }
  22215. }
  22216. return parsedCustomTexture;
  22217. }
  22218. if (parsedTexture.isCube) {
  22219. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22220. }
  22221. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22222. return null;
  22223. }
  22224. var texture = BABYLON.SerializationHelper.Parse(function () {
  22225. if (parsedTexture.mirrorPlane) {
  22226. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22227. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22228. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22229. return mirrorTexture;
  22230. }
  22231. else if (parsedTexture.isRenderTarget) {
  22232. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22233. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22234. return renderTargetTexture;
  22235. }
  22236. else {
  22237. var texture;
  22238. if (parsedTexture.base64String) {
  22239. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22240. }
  22241. else {
  22242. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22243. }
  22244. return texture;
  22245. }
  22246. }, parsedTexture, scene);
  22247. // Update Sampling Mode
  22248. if (parsedTexture.samplingMode) {
  22249. var sampling = parsedTexture.samplingMode;
  22250. if (texture._samplingMode !== sampling) {
  22251. texture.updateSamplingMode(sampling);
  22252. }
  22253. }
  22254. // Animations
  22255. if (parsedTexture.animations) {
  22256. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22257. var parsedAnimation = parsedTexture.animations[animationIndex];
  22258. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22259. }
  22260. }
  22261. return texture;
  22262. };
  22263. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22264. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22265. if (noMipmap === void 0) { noMipmap = false; }
  22266. if (invertY === void 0) { invertY = true; }
  22267. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22268. if (onLoad === void 0) { onLoad = null; }
  22269. if (onError === void 0) { onError = null; }
  22270. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22271. if (name.substr(0, 5) !== "data:") {
  22272. name = "data:" + name;
  22273. }
  22274. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22275. };
  22276. // Constants
  22277. Texture.NEAREST_SAMPLINGMODE = 1;
  22278. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22279. Texture.BILINEAR_SAMPLINGMODE = 2;
  22280. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22281. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22282. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22283. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22284. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22285. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22286. Texture.NEAREST_LINEAR = 7;
  22287. Texture.NEAREST_NEAREST = 8;
  22288. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22289. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22290. Texture.LINEAR_LINEAR = 11;
  22291. Texture.LINEAR_NEAREST = 12;
  22292. Texture.EXPLICIT_MODE = 0;
  22293. Texture.SPHERICAL_MODE = 1;
  22294. Texture.PLANAR_MODE = 2;
  22295. Texture.CUBIC_MODE = 3;
  22296. Texture.PROJECTION_MODE = 4;
  22297. Texture.SKYBOX_MODE = 5;
  22298. Texture.INVCUBIC_MODE = 6;
  22299. Texture.EQUIRECTANGULAR_MODE = 7;
  22300. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22301. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22302. Texture.CLAMP_ADDRESSMODE = 0;
  22303. Texture.WRAP_ADDRESSMODE = 1;
  22304. Texture.MIRROR_ADDRESSMODE = 2;
  22305. __decorate([
  22306. BABYLON.serialize()
  22307. ], Texture.prototype, "url", void 0);
  22308. __decorate([
  22309. BABYLON.serialize()
  22310. ], Texture.prototype, "uOffset", void 0);
  22311. __decorate([
  22312. BABYLON.serialize()
  22313. ], Texture.prototype, "vOffset", void 0);
  22314. __decorate([
  22315. BABYLON.serialize()
  22316. ], Texture.prototype, "uScale", void 0);
  22317. __decorate([
  22318. BABYLON.serialize()
  22319. ], Texture.prototype, "vScale", void 0);
  22320. __decorate([
  22321. BABYLON.serialize()
  22322. ], Texture.prototype, "uAng", void 0);
  22323. __decorate([
  22324. BABYLON.serialize()
  22325. ], Texture.prototype, "vAng", void 0);
  22326. __decorate([
  22327. BABYLON.serialize()
  22328. ], Texture.prototype, "wAng", void 0);
  22329. __decorate([
  22330. BABYLON.serialize()
  22331. ], Texture.prototype, "isBlocking", null);
  22332. return Texture;
  22333. }(BABYLON.BaseTexture));
  22334. BABYLON.Texture = Texture;
  22335. })(BABYLON || (BABYLON = {}));
  22336. //# sourceMappingURL=babylon.texture.js.map
  22337. var BABYLON;
  22338. (function (BABYLON) {
  22339. var _InstancesBatch = /** @class */ (function () {
  22340. function _InstancesBatch() {
  22341. this.mustReturn = false;
  22342. this.visibleInstances = new Array();
  22343. this.renderSelf = new Array();
  22344. }
  22345. return _InstancesBatch;
  22346. }());
  22347. BABYLON._InstancesBatch = _InstancesBatch;
  22348. var Mesh = /** @class */ (function (_super) {
  22349. __extends(Mesh, _super);
  22350. /**
  22351. * @constructor
  22352. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22353. * @param {Scene} scene The scene to add this mesh to.
  22354. * @param {Node} parent The parent of this mesh, if it has one
  22355. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22356. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22357. * When false, achieved by calling a clone(), also passing False.
  22358. * This will make creation of children, recursive.
  22359. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22360. */
  22361. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22362. if (scene === void 0) { scene = null; }
  22363. if (parent === void 0) { parent = null; }
  22364. if (source === void 0) { source = null; }
  22365. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22366. var _this = _super.call(this, name, scene) || this;
  22367. // Events
  22368. /**
  22369. * An event triggered before rendering the mesh
  22370. * @type {BABYLON.Observable}
  22371. */
  22372. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22373. /**
  22374. * An event triggered after rendering the mesh
  22375. * @type {BABYLON.Observable}
  22376. */
  22377. _this.onAfterRenderObservable = new BABYLON.Observable();
  22378. /**
  22379. * An event triggered before drawing the mesh
  22380. * @type {BABYLON.Observable}
  22381. */
  22382. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22383. // Members
  22384. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22385. _this.instances = new Array();
  22386. _this._LODLevels = new Array();
  22387. _this._visibleInstances = {};
  22388. _this._renderIdForInstances = new Array();
  22389. _this._batchCache = new _InstancesBatch();
  22390. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22391. // Use by builder only to know what orientation were the mesh build in.
  22392. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22393. _this.overrideMaterialSideOrientation = null;
  22394. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22395. // Will be used to save a source mesh reference, If any
  22396. _this._source = null;
  22397. scene = _this.getScene();
  22398. if (source) {
  22399. // Source mesh
  22400. _this._source = source;
  22401. // Geometry
  22402. if (source._geometry) {
  22403. source._geometry.applyToMesh(_this);
  22404. }
  22405. // Deep copy
  22406. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  22407. // Tags
  22408. if (BABYLON.Tags.HasTags(source)) {
  22409. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22410. }
  22411. _this.metadata = source.metadata;
  22412. // Parent
  22413. _this.parent = source.parent;
  22414. // Pivot
  22415. _this.setPivotMatrix(source.getPivotMatrix());
  22416. _this.id = name + "." + source.id;
  22417. // Material
  22418. _this.material = source.material;
  22419. var index;
  22420. if (!doNotCloneChildren) {
  22421. // Children
  22422. for (index = 0; index < scene.meshes.length; index++) {
  22423. var mesh = scene.meshes[index];
  22424. if (mesh.parent === source) {
  22425. // doNotCloneChildren is always going to be False
  22426. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22427. }
  22428. }
  22429. }
  22430. // Physics clone
  22431. var physicsEngine = _this.getScene().getPhysicsEngine();
  22432. if (clonePhysicsImpostor && physicsEngine) {
  22433. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22434. if (impostor) {
  22435. _this.physicsImpostor = impostor.clone(_this);
  22436. }
  22437. }
  22438. // Particles
  22439. for (index = 0; index < scene.particleSystems.length; index++) {
  22440. var system = scene.particleSystems[index];
  22441. if (system.emitter === source) {
  22442. system.clone(system.name, _this);
  22443. }
  22444. }
  22445. _this.computeWorldMatrix(true);
  22446. }
  22447. // Parent
  22448. if (parent !== null) {
  22449. _this.parent = parent;
  22450. }
  22451. return _this;
  22452. }
  22453. Object.defineProperty(Mesh, "FRONTSIDE", {
  22454. /**
  22455. * Mesh side orientation : usually the external or front surface
  22456. */
  22457. get: function () {
  22458. return Mesh._FRONTSIDE;
  22459. },
  22460. enumerable: true,
  22461. configurable: true
  22462. });
  22463. Object.defineProperty(Mesh, "BACKSIDE", {
  22464. /**
  22465. * Mesh side orientation : usually the internal or back surface
  22466. */
  22467. get: function () {
  22468. return Mesh._BACKSIDE;
  22469. },
  22470. enumerable: true,
  22471. configurable: true
  22472. });
  22473. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22474. /**
  22475. * Mesh side orientation : both internal and external or front and back surfaces
  22476. */
  22477. get: function () {
  22478. return Mesh._DOUBLESIDE;
  22479. },
  22480. enumerable: true,
  22481. configurable: true
  22482. });
  22483. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22484. /**
  22485. * Mesh side orientation : by default, `FRONTSIDE`
  22486. */
  22487. get: function () {
  22488. return Mesh._DEFAULTSIDE;
  22489. },
  22490. enumerable: true,
  22491. configurable: true
  22492. });
  22493. Object.defineProperty(Mesh, "NO_CAP", {
  22494. /**
  22495. * Mesh cap setting : no cap
  22496. */
  22497. get: function () {
  22498. return Mesh._NO_CAP;
  22499. },
  22500. enumerable: true,
  22501. configurable: true
  22502. });
  22503. Object.defineProperty(Mesh, "CAP_START", {
  22504. /**
  22505. * Mesh cap setting : one cap at the beginning of the mesh
  22506. */
  22507. get: function () {
  22508. return Mesh._CAP_START;
  22509. },
  22510. enumerable: true,
  22511. configurable: true
  22512. });
  22513. Object.defineProperty(Mesh, "CAP_END", {
  22514. /**
  22515. * Mesh cap setting : one cap at the end of the mesh
  22516. */
  22517. get: function () {
  22518. return Mesh._CAP_END;
  22519. },
  22520. enumerable: true,
  22521. configurable: true
  22522. });
  22523. Object.defineProperty(Mesh, "CAP_ALL", {
  22524. /**
  22525. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22526. */
  22527. get: function () {
  22528. return Mesh._CAP_ALL;
  22529. },
  22530. enumerable: true,
  22531. configurable: true
  22532. });
  22533. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22534. set: function (callback) {
  22535. if (this._onBeforeDrawObserver) {
  22536. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22537. }
  22538. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22539. },
  22540. enumerable: true,
  22541. configurable: true
  22542. });
  22543. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  22544. get: function () {
  22545. return this._morphTargetManager;
  22546. },
  22547. set: function (value) {
  22548. if (this._morphTargetManager === value) {
  22549. return;
  22550. }
  22551. this._morphTargetManager = value;
  22552. this._syncGeometryWithMorphTargetManager();
  22553. },
  22554. enumerable: true,
  22555. configurable: true
  22556. });
  22557. Object.defineProperty(Mesh.prototype, "source", {
  22558. get: function () {
  22559. return this._source;
  22560. },
  22561. enumerable: true,
  22562. configurable: true
  22563. });
  22564. // Methods
  22565. /**
  22566. * Returns the string "Mesh".
  22567. */
  22568. Mesh.prototype.getClassName = function () {
  22569. return "Mesh";
  22570. };
  22571. /**
  22572. * Returns a string.
  22573. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22574. */
  22575. Mesh.prototype.toString = function (fullDetails) {
  22576. var ret = _super.prototype.toString.call(this, fullDetails);
  22577. ret += ", n vertices: " + this.getTotalVertices();
  22578. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22579. if (this.animations) {
  22580. for (var i = 0; i < this.animations.length; i++) {
  22581. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22582. }
  22583. }
  22584. if (fullDetails) {
  22585. if (this._geometry) {
  22586. var ib = this.getIndices();
  22587. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22588. if (vb && ib) {
  22589. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  22590. }
  22591. }
  22592. else {
  22593. ret += ", flat shading: UNKNOWN";
  22594. }
  22595. }
  22596. return ret;
  22597. };
  22598. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22599. /**
  22600. * True if the mesh has some Levels Of Details (LOD).
  22601. * Returns a boolean.
  22602. */
  22603. get: function () {
  22604. return this._LODLevels.length > 0;
  22605. },
  22606. enumerable: true,
  22607. configurable: true
  22608. });
  22609. Mesh.prototype._sortLODLevels = function () {
  22610. this._LODLevels.sort(function (a, b) {
  22611. if (a.distance < b.distance) {
  22612. return 1;
  22613. }
  22614. if (a.distance > b.distance) {
  22615. return -1;
  22616. }
  22617. return 0;
  22618. });
  22619. };
  22620. /**
  22621. * Add a mesh as LOD level triggered at the given distance.
  22622. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22623. * @param {number} distance The distance from the center of the object to show this level
  22624. * @param {Mesh} mesh The mesh to be added as LOD level
  22625. * @return {Mesh} This mesh (for chaining)
  22626. */
  22627. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22628. if (mesh && mesh._masterMesh) {
  22629. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22630. return this;
  22631. }
  22632. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22633. this._LODLevels.push(level);
  22634. if (mesh) {
  22635. mesh._masterMesh = this;
  22636. }
  22637. this._sortLODLevels();
  22638. return this;
  22639. };
  22640. /**
  22641. * Returns the LOD level mesh at the passed distance or null if not found.
  22642. * It is related to the method `addLODLevel(distance, mesh)`.
  22643. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22644. * Returns an object Mesh or `null`.
  22645. */
  22646. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22647. for (var index = 0; index < this._LODLevels.length; index++) {
  22648. var level = this._LODLevels[index];
  22649. if (level.distance === distance) {
  22650. return level.mesh;
  22651. }
  22652. }
  22653. return null;
  22654. };
  22655. /**
  22656. * Remove a mesh from the LOD array
  22657. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22658. * @param {Mesh} mesh The mesh to be removed.
  22659. * @return {Mesh} This mesh (for chaining)
  22660. */
  22661. Mesh.prototype.removeLODLevel = function (mesh) {
  22662. for (var index = 0; index < this._LODLevels.length; index++) {
  22663. if (this._LODLevels[index].mesh === mesh) {
  22664. this._LODLevels.splice(index, 1);
  22665. if (mesh) {
  22666. mesh._masterMesh = null;
  22667. }
  22668. }
  22669. }
  22670. this._sortLODLevels();
  22671. return this;
  22672. };
  22673. /**
  22674. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22675. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22676. */
  22677. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22678. if (!this._LODLevels || this._LODLevels.length === 0) {
  22679. return this;
  22680. }
  22681. var bSphere;
  22682. if (boundingSphere) {
  22683. bSphere = boundingSphere;
  22684. }
  22685. else {
  22686. var boundingInfo = this.getBoundingInfo();
  22687. if (!boundingInfo) {
  22688. return this;
  22689. }
  22690. bSphere = boundingInfo.boundingSphere;
  22691. }
  22692. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  22693. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22694. if (this.onLODLevelSelection) {
  22695. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22696. }
  22697. return this;
  22698. }
  22699. for (var index = 0; index < this._LODLevels.length; index++) {
  22700. var level = this._LODLevels[index];
  22701. if (level.distance < distanceToCamera) {
  22702. if (level.mesh) {
  22703. level.mesh._preActivate();
  22704. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22705. }
  22706. if (this.onLODLevelSelection) {
  22707. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22708. }
  22709. return level.mesh;
  22710. }
  22711. }
  22712. if (this.onLODLevelSelection) {
  22713. this.onLODLevelSelection(distanceToCamera, this, this);
  22714. }
  22715. return this;
  22716. };
  22717. Object.defineProperty(Mesh.prototype, "geometry", {
  22718. /**
  22719. * Returns the mesh internal Geometry object.
  22720. */
  22721. get: function () {
  22722. return this._geometry;
  22723. },
  22724. enumerable: true,
  22725. configurable: true
  22726. });
  22727. /**
  22728. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22729. */
  22730. Mesh.prototype.getTotalVertices = function () {
  22731. if (!this._geometry) {
  22732. return 0;
  22733. }
  22734. return this._geometry.getTotalVertices();
  22735. };
  22736. /**
  22737. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22738. * 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.
  22739. * You can force the copy with forceCopy === true
  22740. * Returns null if the mesh has no geometry or no vertex buffer.
  22741. * Possible `kind` values :
  22742. * - BABYLON.VertexBuffer.PositionKind
  22743. * - BABYLON.VertexBuffer.UVKind
  22744. * - BABYLON.VertexBuffer.UV2Kind
  22745. * - BABYLON.VertexBuffer.UV3Kind
  22746. * - BABYLON.VertexBuffer.UV4Kind
  22747. * - BABYLON.VertexBuffer.UV5Kind
  22748. * - BABYLON.VertexBuffer.UV6Kind
  22749. * - BABYLON.VertexBuffer.ColorKind
  22750. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22751. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22752. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22753. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22754. */
  22755. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  22756. if (!this._geometry) {
  22757. return null;
  22758. }
  22759. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  22760. };
  22761. /**
  22762. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22763. * Returns `null` if the mesh has no geometry.
  22764. * Possible `kind` values :
  22765. * - BABYLON.VertexBuffer.PositionKind
  22766. * - BABYLON.VertexBuffer.UVKind
  22767. * - BABYLON.VertexBuffer.UV2Kind
  22768. * - BABYLON.VertexBuffer.UV3Kind
  22769. * - BABYLON.VertexBuffer.UV4Kind
  22770. * - BABYLON.VertexBuffer.UV5Kind
  22771. * - BABYLON.VertexBuffer.UV6Kind
  22772. * - BABYLON.VertexBuffer.ColorKind
  22773. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22774. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22775. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22776. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22777. */
  22778. Mesh.prototype.getVertexBuffer = function (kind) {
  22779. if (!this._geometry) {
  22780. return null;
  22781. }
  22782. return this._geometry.getVertexBuffer(kind);
  22783. };
  22784. /**
  22785. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22786. * Possible `kind` values :
  22787. * - BABYLON.VertexBuffer.PositionKind
  22788. * - BABYLON.VertexBuffer.UVKind
  22789. * - BABYLON.VertexBuffer.UV2Kind
  22790. * - BABYLON.VertexBuffer.UV3Kind
  22791. * - BABYLON.VertexBuffer.UV4Kind
  22792. * - BABYLON.VertexBuffer.UV5Kind
  22793. * - BABYLON.VertexBuffer.UV6Kind
  22794. * - BABYLON.VertexBuffer.ColorKind
  22795. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22796. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22797. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22798. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22799. */
  22800. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22801. if (!this._geometry) {
  22802. if (this._delayInfo) {
  22803. return this._delayInfo.indexOf(kind) !== -1;
  22804. }
  22805. return false;
  22806. }
  22807. return this._geometry.isVerticesDataPresent(kind);
  22808. };
  22809. /**
  22810. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  22811. * Possible `kind` values :
  22812. * - BABYLON.VertexBuffer.PositionKind
  22813. * - BABYLON.VertexBuffer.UVKind
  22814. * - BABYLON.VertexBuffer.UV2Kind
  22815. * - BABYLON.VertexBuffer.UV3Kind
  22816. * - BABYLON.VertexBuffer.UV4Kind
  22817. * - BABYLON.VertexBuffer.UV5Kind
  22818. * - BABYLON.VertexBuffer.UV6Kind
  22819. * - BABYLON.VertexBuffer.ColorKind
  22820. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22821. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22822. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22823. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22824. */
  22825. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  22826. if (!this._geometry) {
  22827. if (this._delayInfo) {
  22828. return this._delayInfo.indexOf(kind) !== -1;
  22829. }
  22830. return false;
  22831. }
  22832. return this._geometry.isVertexBufferUpdatable(kind);
  22833. };
  22834. /**
  22835. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22836. * Possible `kind` values :
  22837. * - BABYLON.VertexBuffer.PositionKind
  22838. * - BABYLON.VertexBuffer.UVKind
  22839. * - BABYLON.VertexBuffer.UV2Kind
  22840. * - BABYLON.VertexBuffer.UV3Kind
  22841. * - BABYLON.VertexBuffer.UV4Kind
  22842. * - BABYLON.VertexBuffer.UV5Kind
  22843. * - BABYLON.VertexBuffer.UV6Kind
  22844. * - BABYLON.VertexBuffer.ColorKind
  22845. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22846. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22847. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22848. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22849. */
  22850. Mesh.prototype.getVerticesDataKinds = function () {
  22851. if (!this._geometry) {
  22852. var result = new Array();
  22853. if (this._delayInfo) {
  22854. this._delayInfo.forEach(function (kind, index, array) {
  22855. result.push(kind);
  22856. });
  22857. }
  22858. return result;
  22859. }
  22860. return this._geometry.getVerticesDataKinds();
  22861. };
  22862. /**
  22863. * Returns a positive integer : the total number of indices in this mesh geometry.
  22864. * Returns zero if the mesh has no geometry.
  22865. */
  22866. Mesh.prototype.getTotalIndices = function () {
  22867. if (!this._geometry) {
  22868. return 0;
  22869. }
  22870. return this._geometry.getTotalIndices();
  22871. };
  22872. /**
  22873. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22874. * 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.
  22875. * Returns an empty array if the mesh has no geometry.
  22876. */
  22877. Mesh.prototype.getIndices = function (copyWhenShared) {
  22878. if (!this._geometry) {
  22879. return [];
  22880. }
  22881. return this._geometry.getIndices(copyWhenShared);
  22882. };
  22883. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22884. get: function () {
  22885. return this._masterMesh !== null && this._masterMesh !== undefined;
  22886. },
  22887. enumerable: true,
  22888. configurable: true
  22889. });
  22890. /**
  22891. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22892. */
  22893. Mesh.prototype.isReady = function () {
  22894. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22895. return false;
  22896. }
  22897. return _super.prototype.isReady.call(this);
  22898. };
  22899. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22900. /**
  22901. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22902. * This property is pertinent only for updatable parametric shapes.
  22903. */
  22904. get: function () {
  22905. return this._areNormalsFrozen;
  22906. },
  22907. enumerable: true,
  22908. configurable: true
  22909. });
  22910. /**
  22911. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22912. * It has no effect at all on other shapes.
  22913. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22914. * Returns the Mesh.
  22915. */
  22916. Mesh.prototype.freezeNormals = function () {
  22917. this._areNormalsFrozen = true;
  22918. return this;
  22919. };
  22920. /**
  22921. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22922. * It has no effect at all on other shapes.
  22923. * It reactivates the mesh normals computation if it was previously frozen.
  22924. * Returns the Mesh.
  22925. */
  22926. Mesh.prototype.unfreezeNormals = function () {
  22927. this._areNormalsFrozen = false;
  22928. return this;
  22929. };
  22930. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22931. /**
  22932. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22933. */
  22934. set: function (count) {
  22935. this._overridenInstanceCount = count;
  22936. },
  22937. enumerable: true,
  22938. configurable: true
  22939. });
  22940. // Methods
  22941. Mesh.prototype._preActivate = function () {
  22942. var sceneRenderId = this.getScene().getRenderId();
  22943. if (this._preActivateId === sceneRenderId) {
  22944. return this;
  22945. }
  22946. this._preActivateId = sceneRenderId;
  22947. this._visibleInstances = null;
  22948. return this;
  22949. };
  22950. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22951. if (this._visibleInstances) {
  22952. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22953. }
  22954. return this;
  22955. };
  22956. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22957. if (!this._visibleInstances) {
  22958. this._visibleInstances = {};
  22959. this._visibleInstances.defaultRenderId = renderId;
  22960. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22961. }
  22962. if (!this._visibleInstances[renderId]) {
  22963. this._visibleInstances[renderId] = new Array();
  22964. }
  22965. this._visibleInstances[renderId].push(instance);
  22966. return this;
  22967. };
  22968. /**
  22969. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22970. * This means the mesh underlying bounding box and sphere are recomputed.
  22971. * Returns the Mesh.
  22972. */
  22973. Mesh.prototype.refreshBoundingInfo = function () {
  22974. if (this._boundingInfo && this._boundingInfo.isLocked) {
  22975. return this;
  22976. }
  22977. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22978. if (data) {
  22979. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22980. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22981. }
  22982. if (this.subMeshes) {
  22983. for (var index = 0; index < this.subMeshes.length; index++) {
  22984. this.subMeshes[index].refreshBoundingInfo();
  22985. }
  22986. }
  22987. this._updateBoundingInfo();
  22988. return this;
  22989. };
  22990. Mesh.prototype._createGlobalSubMesh = function (force) {
  22991. var totalVertices = this.getTotalVertices();
  22992. if (!totalVertices || !this.getIndices()) {
  22993. return null;
  22994. }
  22995. // Check if we need to recreate the submeshes
  22996. if (this.subMeshes && this.subMeshes.length > 0) {
  22997. var ib = this.getIndices();
  22998. if (!ib) {
  22999. return null;
  23000. }
  23001. var totalIndices = ib.length;
  23002. var needToRecreate = false;
  23003. if (force) {
  23004. needToRecreate = true;
  23005. }
  23006. else {
  23007. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23008. var submesh = _a[_i];
  23009. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23010. needToRecreate = true;
  23011. break;
  23012. }
  23013. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23014. needToRecreate = true;
  23015. break;
  23016. }
  23017. }
  23018. }
  23019. if (!needToRecreate) {
  23020. return this.subMeshes[0];
  23021. }
  23022. }
  23023. this.releaseSubMeshes();
  23024. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23025. };
  23026. Mesh.prototype.subdivide = function (count) {
  23027. if (count < 1) {
  23028. return;
  23029. }
  23030. var totalIndices = this.getTotalIndices();
  23031. var subdivisionSize = (totalIndices / count) | 0;
  23032. var offset = 0;
  23033. // Ensure that subdivisionSize is a multiple of 3
  23034. while (subdivisionSize % 3 !== 0) {
  23035. subdivisionSize++;
  23036. }
  23037. this.releaseSubMeshes();
  23038. for (var index = 0; index < count; index++) {
  23039. if (offset >= totalIndices) {
  23040. break;
  23041. }
  23042. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23043. offset += subdivisionSize;
  23044. }
  23045. this.synchronizeInstances();
  23046. };
  23047. /**
  23048. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23049. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23050. * The `data` are either a numeric array either a Float32Array.
  23051. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23052. * 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).
  23053. * Note that a new underlying VertexBuffer object is created each call.
  23054. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23055. *
  23056. * Possible `kind` values :
  23057. * - BABYLON.VertexBuffer.PositionKind
  23058. * - BABYLON.VertexBuffer.UVKind
  23059. * - BABYLON.VertexBuffer.UV2Kind
  23060. * - BABYLON.VertexBuffer.UV3Kind
  23061. * - BABYLON.VertexBuffer.UV4Kind
  23062. * - BABYLON.VertexBuffer.UV5Kind
  23063. * - BABYLON.VertexBuffer.UV6Kind
  23064. * - BABYLON.VertexBuffer.ColorKind
  23065. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23066. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23067. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23068. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23069. *
  23070. * Returns the Mesh.
  23071. */
  23072. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23073. if (updatable === void 0) { updatable = false; }
  23074. if (!this._geometry) {
  23075. var vertexData = new BABYLON.VertexData();
  23076. vertexData.set(data, kind);
  23077. var scene = this.getScene();
  23078. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23079. }
  23080. else {
  23081. this._geometry.setVerticesData(kind, data, updatable, stride);
  23082. }
  23083. return this;
  23084. };
  23085. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23086. if (updatable === void 0) { updatable = true; }
  23087. var vb = this.getVertexBuffer(kind);
  23088. if (!vb || vb.isUpdatable() === updatable) {
  23089. return;
  23090. }
  23091. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23092. };
  23093. /**
  23094. * Sets the mesh VertexBuffer.
  23095. * Returns the Mesh.
  23096. */
  23097. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23098. if (!this._geometry) {
  23099. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23100. }
  23101. this._geometry.setVerticesBuffer(buffer);
  23102. return this;
  23103. };
  23104. /**
  23105. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23106. * If the mesh has no geometry, it is simply returned as it is.
  23107. * The `data` are either a numeric array either a Float32Array.
  23108. * No new underlying VertexBuffer object is created.
  23109. * 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.
  23110. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23111. *
  23112. * Possible `kind` values :
  23113. * - BABYLON.VertexBuffer.PositionKind
  23114. * - BABYLON.VertexBuffer.UVKind
  23115. * - BABYLON.VertexBuffer.UV2Kind
  23116. * - BABYLON.VertexBuffer.UV3Kind
  23117. * - BABYLON.VertexBuffer.UV4Kind
  23118. * - BABYLON.VertexBuffer.UV5Kind
  23119. * - BABYLON.VertexBuffer.UV6Kind
  23120. * - BABYLON.VertexBuffer.ColorKind
  23121. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23122. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23123. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23124. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23125. *
  23126. * Returns the Mesh.
  23127. */
  23128. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23129. if (!this._geometry) {
  23130. return this;
  23131. }
  23132. if (!makeItUnique) {
  23133. this._geometry.updateVerticesData(kind, data, updateExtends);
  23134. }
  23135. else {
  23136. this.makeGeometryUnique();
  23137. this.updateVerticesData(kind, data, updateExtends, false);
  23138. }
  23139. return this;
  23140. };
  23141. /**
  23142. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23143. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23144. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23145. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23146. * Returns the Mesh.
  23147. */
  23148. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23149. if (computeNormals === void 0) { computeNormals = true; }
  23150. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23151. if (!positions) {
  23152. return this;
  23153. }
  23154. positionFunction(positions);
  23155. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23156. if (computeNormals) {
  23157. var indices = this.getIndices();
  23158. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23159. if (!normals) {
  23160. return this;
  23161. }
  23162. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23163. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23164. }
  23165. return this;
  23166. };
  23167. /**
  23168. * Creates a un-shared specific occurence of the geometry for the mesh.
  23169. * Returns the Mesh.
  23170. */
  23171. Mesh.prototype.makeGeometryUnique = function () {
  23172. if (!this._geometry) {
  23173. return this;
  23174. }
  23175. var oldGeometry = this._geometry;
  23176. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23177. oldGeometry.releaseForMesh(this, true);
  23178. geometry.applyToMesh(this);
  23179. return this;
  23180. };
  23181. /**
  23182. * Sets the mesh indices.
  23183. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23184. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23185. * This method creates a new index buffer each call.
  23186. * Returns the Mesh.
  23187. */
  23188. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23189. if (totalVertices === void 0) { totalVertices = null; }
  23190. if (updatable === void 0) { updatable = false; }
  23191. if (!this._geometry) {
  23192. var vertexData = new BABYLON.VertexData();
  23193. vertexData.indices = indices;
  23194. var scene = this.getScene();
  23195. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23196. }
  23197. else {
  23198. this._geometry.setIndices(indices, totalVertices, updatable);
  23199. }
  23200. return this;
  23201. };
  23202. /**
  23203. * Update the current index buffer
  23204. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23205. * Returns the Mesh.
  23206. */
  23207. Mesh.prototype.updateIndices = function (indices, offset) {
  23208. if (!this._geometry) {
  23209. return this;
  23210. }
  23211. this._geometry.updateIndices(indices, offset);
  23212. return this;
  23213. };
  23214. /**
  23215. * Invert the geometry to move from a right handed system to a left handed one.
  23216. * Returns the Mesh.
  23217. */
  23218. Mesh.prototype.toLeftHanded = function () {
  23219. if (!this._geometry) {
  23220. return this;
  23221. }
  23222. this._geometry.toLeftHanded();
  23223. return this;
  23224. };
  23225. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23226. if (!this._geometry) {
  23227. return this;
  23228. }
  23229. var engine = this.getScene().getEngine();
  23230. // Wireframe
  23231. var indexToBind;
  23232. if (this._unIndexed) {
  23233. indexToBind = null;
  23234. }
  23235. else {
  23236. switch (fillMode) {
  23237. case BABYLON.Material.PointFillMode:
  23238. indexToBind = null;
  23239. break;
  23240. case BABYLON.Material.WireFrameFillMode:
  23241. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23242. break;
  23243. default:
  23244. case BABYLON.Material.TriangleFillMode:
  23245. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23246. break;
  23247. }
  23248. }
  23249. // VBOs
  23250. this._geometry._bind(effect, indexToBind);
  23251. return this;
  23252. };
  23253. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23254. if (alternate === void 0) { alternate = false; }
  23255. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23256. return this;
  23257. }
  23258. this.onBeforeDrawObservable.notifyObservers(this);
  23259. var scene = this.getScene();
  23260. var engine = scene.getEngine();
  23261. // Draw order
  23262. switch (fillMode) {
  23263. case BABYLON.Material.PointFillMode:
  23264. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23265. break;
  23266. case BABYLON.Material.WireFrameFillMode:
  23267. if (this._unIndexed) {
  23268. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23269. }
  23270. else {
  23271. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23272. }
  23273. break;
  23274. default:
  23275. if (this._unIndexed) {
  23276. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23277. }
  23278. else {
  23279. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23280. }
  23281. }
  23282. if (scene._isAlternateRenderingEnabled && !alternate) {
  23283. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23284. if (!effect || !scene.activeCamera) {
  23285. return this;
  23286. }
  23287. scene._switchToAlternateCameraConfiguration(true);
  23288. this._effectiveMaterial.bindView(effect);
  23289. this._effectiveMaterial.bindViewProjection(effect);
  23290. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23291. this._draw(subMesh, fillMode, instancesCount, true);
  23292. engine.setViewport(scene.activeCamera.viewport);
  23293. scene._switchToAlternateCameraConfiguration(false);
  23294. this._effectiveMaterial.bindView(effect);
  23295. this._effectiveMaterial.bindViewProjection(effect);
  23296. }
  23297. return this;
  23298. };
  23299. /**
  23300. * Registers for this mesh a javascript function called just before the rendering process.
  23301. * This function is passed the current mesh.
  23302. * Return the Mesh.
  23303. */
  23304. Mesh.prototype.registerBeforeRender = function (func) {
  23305. this.onBeforeRenderObservable.add(func);
  23306. return this;
  23307. };
  23308. /**
  23309. * Disposes a previously registered javascript function called before the rendering.
  23310. * This function is passed the current mesh.
  23311. * Returns the Mesh.
  23312. */
  23313. Mesh.prototype.unregisterBeforeRender = function (func) {
  23314. this.onBeforeRenderObservable.removeCallback(func);
  23315. return this;
  23316. };
  23317. /**
  23318. * Registers for this mesh a javascript function called just after the rendering is complete.
  23319. * This function is passed the current mesh.
  23320. * Returns the Mesh.
  23321. */
  23322. Mesh.prototype.registerAfterRender = function (func) {
  23323. this.onAfterRenderObservable.add(func);
  23324. return this;
  23325. };
  23326. /**
  23327. * Disposes a previously registered javascript function called after the rendering.
  23328. * This function is passed the current mesh.
  23329. * Return the Mesh.
  23330. */
  23331. Mesh.prototype.unregisterAfterRender = function (func) {
  23332. this.onAfterRenderObservable.removeCallback(func);
  23333. return this;
  23334. };
  23335. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23336. var scene = this.getScene();
  23337. this._batchCache.mustReturn = false;
  23338. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23339. this._batchCache.visibleInstances[subMeshId] = null;
  23340. if (this._visibleInstances) {
  23341. var currentRenderId = scene.getRenderId();
  23342. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23343. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23344. var selfRenderId = this._renderId;
  23345. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23346. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23347. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23348. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23349. }
  23350. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23351. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23352. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23353. this._batchCache.mustReturn = true;
  23354. return this._batchCache;
  23355. }
  23356. if (currentRenderId !== selfRenderId) {
  23357. this._batchCache.renderSelf[subMeshId] = false;
  23358. }
  23359. }
  23360. this._renderIdForInstances[subMeshId] = currentRenderId;
  23361. }
  23362. return this._batchCache;
  23363. };
  23364. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23365. var visibleInstances = batch.visibleInstances[subMesh._id];
  23366. if (!visibleInstances) {
  23367. return this;
  23368. }
  23369. var matricesCount = visibleInstances.length + 1;
  23370. var bufferSize = matricesCount * 16 * 4;
  23371. var currentInstancesBufferSize = this._instancesBufferSize;
  23372. var instancesBuffer = this._instancesBuffer;
  23373. while (this._instancesBufferSize < bufferSize) {
  23374. this._instancesBufferSize *= 2;
  23375. }
  23376. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23377. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23378. }
  23379. var offset = 0;
  23380. var instancesCount = 0;
  23381. var world = this.getWorldMatrix();
  23382. if (batch.renderSelf[subMesh._id]) {
  23383. world.copyToArray(this._instancesData, offset);
  23384. offset += 16;
  23385. instancesCount++;
  23386. }
  23387. if (visibleInstances) {
  23388. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23389. var instance = visibleInstances[instanceIndex];
  23390. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23391. offset += 16;
  23392. instancesCount++;
  23393. }
  23394. }
  23395. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23396. if (instancesBuffer) {
  23397. instancesBuffer.dispose();
  23398. }
  23399. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23400. this._instancesBuffer = instancesBuffer;
  23401. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23402. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23403. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23404. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23405. }
  23406. else {
  23407. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23408. }
  23409. this._bind(subMesh, effect, fillMode);
  23410. this._draw(subMesh, fillMode, instancesCount);
  23411. engine.unbindInstanceAttributes();
  23412. return this;
  23413. };
  23414. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23415. var scene = this.getScene();
  23416. var engine = scene.getEngine();
  23417. if (hardwareInstancedRendering) {
  23418. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23419. }
  23420. else {
  23421. if (batch.renderSelf[subMesh._id]) {
  23422. // Draw
  23423. if (onBeforeDraw) {
  23424. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23425. }
  23426. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23427. }
  23428. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23429. if (visibleInstancesForSubMesh) {
  23430. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23431. var instance = visibleInstancesForSubMesh[instanceIndex];
  23432. // World
  23433. var world = instance.getWorldMatrix();
  23434. if (onBeforeDraw) {
  23435. onBeforeDraw(true, world, effectiveMaterial);
  23436. }
  23437. // Draw
  23438. this._draw(subMesh, fillMode);
  23439. }
  23440. }
  23441. }
  23442. return this;
  23443. };
  23444. /**
  23445. * Triggers the draw call for the mesh.
  23446. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23447. * Returns the Mesh.
  23448. */
  23449. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23450. this.checkOcclusionQuery();
  23451. if (this._isOccluded) {
  23452. return this;
  23453. }
  23454. var scene = this.getScene();
  23455. // Managing instances
  23456. var batch = this._getInstancesRenderList(subMesh._id);
  23457. if (batch.mustReturn) {
  23458. return this;
  23459. }
  23460. // Checking geometry state
  23461. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23462. return this;
  23463. }
  23464. this.onBeforeRenderObservable.notifyObservers(this);
  23465. var engine = scene.getEngine();
  23466. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23467. // Material
  23468. var material = subMesh.getMaterial();
  23469. if (!material) {
  23470. return this;
  23471. }
  23472. this._effectiveMaterial = material;
  23473. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23474. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  23475. return this;
  23476. }
  23477. }
  23478. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23479. return this;
  23480. }
  23481. // Alpha mode
  23482. if (enableAlphaMode) {
  23483. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  23484. }
  23485. // Outline - step 1
  23486. var savedDepthWrite = engine.getDepthWrite();
  23487. if (this.renderOutline) {
  23488. engine.setDepthWrite(false);
  23489. scene.getOutlineRenderer().render(subMesh, batch);
  23490. engine.setDepthWrite(savedDepthWrite);
  23491. }
  23492. var effect;
  23493. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23494. effect = subMesh.effect;
  23495. }
  23496. else {
  23497. effect = this._effectiveMaterial.getEffect();
  23498. }
  23499. if (!effect) {
  23500. return this;
  23501. }
  23502. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  23503. if (this._effectiveMaterial.forceDepthWrite) {
  23504. engine.setDepthWrite(true);
  23505. }
  23506. // Bind
  23507. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  23508. if (!hardwareInstancedRendering) {
  23509. this._bind(subMesh, effect, fillMode);
  23510. }
  23511. var world = this.getWorldMatrix();
  23512. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23513. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  23514. }
  23515. else {
  23516. this._effectiveMaterial.bind(world, this);
  23517. }
  23518. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  23519. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  23520. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23521. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  23522. }
  23523. // Draw
  23524. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23525. // Unbind
  23526. this._effectiveMaterial.unbind();
  23527. // Outline - step 2
  23528. if (this.renderOutline && savedDepthWrite) {
  23529. engine.setDepthWrite(true);
  23530. engine.setColorWrite(false);
  23531. scene.getOutlineRenderer().render(subMesh, batch);
  23532. engine.setColorWrite(true);
  23533. }
  23534. // Overlay
  23535. if (this.renderOverlay) {
  23536. var currentMode = engine.getAlphaMode();
  23537. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23538. scene.getOutlineRenderer().render(subMesh, batch, true);
  23539. engine.setAlphaMode(currentMode);
  23540. }
  23541. this.onAfterRenderObservable.notifyObservers(this);
  23542. return this;
  23543. };
  23544. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23545. if (isInstance) {
  23546. effectiveMaterial.bindOnlyWorldMatrix(world);
  23547. }
  23548. return this;
  23549. };
  23550. /**
  23551. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23552. */
  23553. Mesh.prototype.getEmittedParticleSystems = function () {
  23554. var results = new Array();
  23555. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23556. var particleSystem = this.getScene().particleSystems[index];
  23557. if (particleSystem.emitter === this) {
  23558. results.push(particleSystem);
  23559. }
  23560. }
  23561. return results;
  23562. };
  23563. /**
  23564. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23565. */
  23566. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23567. var results = new Array();
  23568. var descendants = this.getDescendants();
  23569. descendants.push(this);
  23570. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23571. var particleSystem = this.getScene().particleSystems[index];
  23572. var emitter = particleSystem.emitter;
  23573. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  23574. results.push(particleSystem);
  23575. }
  23576. }
  23577. return results;
  23578. };
  23579. Mesh.prototype._checkDelayState = function () {
  23580. var scene = this.getScene();
  23581. if (this._geometry) {
  23582. this._geometry.load(scene);
  23583. }
  23584. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23585. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23586. this._queueLoad(this, scene);
  23587. }
  23588. return this;
  23589. };
  23590. Mesh.prototype._queueLoad = function (mesh, scene) {
  23591. var _this = this;
  23592. scene._addPendingData(mesh);
  23593. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23594. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23595. if (data instanceof ArrayBuffer) {
  23596. _this._delayLoadingFunction(data, _this);
  23597. }
  23598. else {
  23599. _this._delayLoadingFunction(JSON.parse(data), _this);
  23600. }
  23601. _this.instances.forEach(function (instance) {
  23602. instance._syncSubMeshes();
  23603. });
  23604. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23605. scene._removePendingData(_this);
  23606. }, function () { }, scene.database, getBinaryData);
  23607. return this;
  23608. };
  23609. /**
  23610. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23611. */
  23612. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23613. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23614. return false;
  23615. }
  23616. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23617. return false;
  23618. }
  23619. this._checkDelayState();
  23620. return true;
  23621. };
  23622. /**
  23623. * Sets the mesh material by the material or multiMaterial `id` property.
  23624. * The material `id` is a string identifying the material or the multiMaterial.
  23625. * This method returns the Mesh.
  23626. */
  23627. Mesh.prototype.setMaterialByID = function (id) {
  23628. var materials = this.getScene().materials;
  23629. var index;
  23630. for (index = materials.length - 1; index > -1; index--) {
  23631. if (materials[index].id === id) {
  23632. this.material = materials[index];
  23633. return this;
  23634. }
  23635. }
  23636. // Multi
  23637. var multiMaterials = this.getScene().multiMaterials;
  23638. for (index = multiMaterials.length - 1; index > -1; index--) {
  23639. if (multiMaterials[index].id === id) {
  23640. this.material = multiMaterials[index];
  23641. return this;
  23642. }
  23643. }
  23644. return this;
  23645. };
  23646. /**
  23647. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23648. */
  23649. Mesh.prototype.getAnimatables = function () {
  23650. var results = new Array();
  23651. if (this.material) {
  23652. results.push(this.material);
  23653. }
  23654. if (this.skeleton) {
  23655. results.push(this.skeleton);
  23656. }
  23657. return results;
  23658. };
  23659. /**
  23660. * Modifies the mesh geometry according to the passed transformation matrix.
  23661. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23662. * The mesh normals are modified accordingly the same transformation.
  23663. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23664. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23665. * Returns the Mesh.
  23666. */
  23667. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23668. // Position
  23669. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23670. return this;
  23671. }
  23672. var submeshes = this.subMeshes.splice(0);
  23673. this._resetPointsArrayCache();
  23674. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23675. var temp = new Array();
  23676. var index;
  23677. for (index = 0; index < data.length; index += 3) {
  23678. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23679. }
  23680. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23681. // Normals
  23682. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23683. return this;
  23684. }
  23685. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23686. temp = [];
  23687. for (index = 0; index < data.length; index += 3) {
  23688. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23689. }
  23690. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23691. // flip faces?
  23692. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23693. this.flipFaces();
  23694. }
  23695. // Restore submeshes
  23696. this.releaseSubMeshes();
  23697. this.subMeshes = submeshes;
  23698. return this;
  23699. };
  23700. /**
  23701. * Modifies the mesh geometry according to its own current World Matrix.
  23702. * The mesh World Matrix is then reset.
  23703. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23704. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23705. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23706. * Returns the Mesh.
  23707. */
  23708. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23709. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23710. this.scaling.copyFromFloats(1, 1, 1);
  23711. this.position.copyFromFloats(0, 0, 0);
  23712. this.rotation.copyFromFloats(0, 0, 0);
  23713. //only if quaternion is already set
  23714. if (this.rotationQuaternion) {
  23715. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23716. }
  23717. this._worldMatrix = BABYLON.Matrix.Identity();
  23718. return this;
  23719. };
  23720. Object.defineProperty(Mesh.prototype, "_positions", {
  23721. // Cache
  23722. get: function () {
  23723. if (this._geometry) {
  23724. return this._geometry._positions;
  23725. }
  23726. return null;
  23727. },
  23728. enumerable: true,
  23729. configurable: true
  23730. });
  23731. Mesh.prototype._resetPointsArrayCache = function () {
  23732. if (this._geometry) {
  23733. this._geometry._resetPointsArrayCache();
  23734. }
  23735. return this;
  23736. };
  23737. Mesh.prototype._generatePointsArray = function () {
  23738. if (this._geometry) {
  23739. return this._geometry._generatePointsArray();
  23740. }
  23741. return false;
  23742. };
  23743. /**
  23744. * Returns a new Mesh object generated from the current mesh properties.
  23745. * This method must not get confused with createInstance().
  23746. * The parameter `name` is a string, the name given to the new mesh.
  23747. * The optional parameter `newParent` can be any Node object (default `null`).
  23748. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23749. * 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.
  23750. */
  23751. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23752. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23753. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23754. };
  23755. /**
  23756. * Disposes the mesh.
  23757. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23758. */
  23759. Mesh.prototype.dispose = function (doNotRecurse) {
  23760. var _this = this;
  23761. this.morphTargetManager = null;
  23762. if (this._geometry) {
  23763. this._geometry.releaseForMesh(this, true);
  23764. }
  23765. // Sources
  23766. var meshes = this.getScene().meshes;
  23767. meshes.forEach(function (mesh) {
  23768. if (mesh._source && mesh._source === _this) {
  23769. mesh._source = null;
  23770. }
  23771. });
  23772. this._source = null;
  23773. // Instances
  23774. if (this._instancesBuffer) {
  23775. this._instancesBuffer.dispose();
  23776. this._instancesBuffer = null;
  23777. }
  23778. while (this.instances.length) {
  23779. this.instances[0].dispose();
  23780. }
  23781. // Highlight layers.
  23782. var highlightLayers = this.getScene().highlightLayers;
  23783. for (var i = 0; i < highlightLayers.length; i++) {
  23784. var highlightLayer = highlightLayers[i];
  23785. if (highlightLayer) {
  23786. highlightLayer.removeMesh(this);
  23787. highlightLayer.removeExcludedMesh(this);
  23788. }
  23789. }
  23790. _super.prototype.dispose.call(this, doNotRecurse);
  23791. };
  23792. /**
  23793. * Modifies the mesh geometry according to a displacement map.
  23794. * 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.
  23795. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23796. * This method returns nothing.
  23797. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23798. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23799. * 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.
  23800. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23801. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23802. *
  23803. * Returns the Mesh.
  23804. */
  23805. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23806. var _this = this;
  23807. var scene = this.getScene();
  23808. var onload = function (img) {
  23809. // Getting height map data
  23810. var canvas = document.createElement("canvas");
  23811. var context = canvas.getContext("2d");
  23812. var heightMapWidth = img.width;
  23813. var heightMapHeight = img.height;
  23814. canvas.width = heightMapWidth;
  23815. canvas.height = heightMapHeight;
  23816. context.drawImage(img, 0, 0);
  23817. // Create VertexData from map data
  23818. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23819. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23820. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23821. //execute success callback, if set
  23822. if (onSuccess) {
  23823. onSuccess(_this);
  23824. }
  23825. };
  23826. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23827. return this;
  23828. };
  23829. /**
  23830. * Modifies the mesh geometry according to a displacementMap buffer.
  23831. * 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.
  23832. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23833. * This method returns nothing.
  23834. * 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.
  23835. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23836. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23837. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23838. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23839. *
  23840. * Returns the Mesh.
  23841. */
  23842. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23843. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23844. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23845. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23846. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23847. return this;
  23848. }
  23849. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23850. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23851. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23852. var position = BABYLON.Vector3.Zero();
  23853. var normal = BABYLON.Vector3.Zero();
  23854. var uv = BABYLON.Vector2.Zero();
  23855. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23856. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23857. for (var index = 0; index < positions.length; index += 3) {
  23858. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23859. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23860. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23861. // Compute height
  23862. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23863. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23864. var pos = (u + v * heightMapWidth) * 4;
  23865. var r = buffer[pos] / 255.0;
  23866. var g = buffer[pos + 1] / 255.0;
  23867. var b = buffer[pos + 2] / 255.0;
  23868. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23869. normal.normalize();
  23870. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23871. position = position.add(normal);
  23872. position.toArray(positions, index);
  23873. }
  23874. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23875. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23876. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23877. return this;
  23878. };
  23879. /**
  23880. * Modify the mesh to get a flat shading rendering.
  23881. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23882. * This method returns the Mesh.
  23883. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23884. */
  23885. Mesh.prototype.convertToFlatShadedMesh = function () {
  23886. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23887. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23888. var kinds = this.getVerticesDataKinds();
  23889. var vbs = {};
  23890. var data = {};
  23891. var newdata = {};
  23892. var updatableNormals = false;
  23893. var kindIndex;
  23894. var kind;
  23895. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23896. kind = kinds[kindIndex];
  23897. var vertexBuffer = this.getVertexBuffer(kind);
  23898. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23899. updatableNormals = vertexBuffer.isUpdatable();
  23900. kinds.splice(kindIndex, 1);
  23901. kindIndex--;
  23902. continue;
  23903. }
  23904. vbs[kind] = vertexBuffer;
  23905. data[kind] = vbs[kind].getData();
  23906. newdata[kind] = [];
  23907. }
  23908. // Save previous submeshes
  23909. var previousSubmeshes = this.subMeshes.slice(0);
  23910. var indices = this.getIndices();
  23911. var totalIndices = this.getTotalIndices();
  23912. // Generating unique vertices per face
  23913. var index;
  23914. for (index = 0; index < totalIndices; index++) {
  23915. var vertexIndex = indices[index];
  23916. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23917. kind = kinds[kindIndex];
  23918. var stride = vbs[kind].getStrideSize();
  23919. for (var offset = 0; offset < stride; offset++) {
  23920. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23921. }
  23922. }
  23923. }
  23924. // Updating faces & normal
  23925. var normals = [];
  23926. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23927. for (index = 0; index < totalIndices; index += 3) {
  23928. indices[index] = index;
  23929. indices[index + 1] = index + 1;
  23930. indices[index + 2] = index + 2;
  23931. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23932. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23933. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23934. var p1p2 = p1.subtract(p2);
  23935. var p3p2 = p3.subtract(p2);
  23936. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23937. // Store same normals for every vertex
  23938. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23939. normals.push(normal.x);
  23940. normals.push(normal.y);
  23941. normals.push(normal.z);
  23942. }
  23943. }
  23944. this.setIndices(indices);
  23945. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23946. // Updating vertex buffers
  23947. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23948. kind = kinds[kindIndex];
  23949. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23950. }
  23951. // Updating submeshes
  23952. this.releaseSubMeshes();
  23953. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23954. var previousOne = previousSubmeshes[submeshIndex];
  23955. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23956. }
  23957. this.synchronizeInstances();
  23958. return this;
  23959. };
  23960. /**
  23961. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23962. * In other words, more vertices, no more indices and a single bigger VBO.
  23963. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23964. * Returns the Mesh.
  23965. */
  23966. Mesh.prototype.convertToUnIndexedMesh = function () {
  23967. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23968. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23969. var kinds = this.getVerticesDataKinds();
  23970. var vbs = {};
  23971. var data = {};
  23972. var newdata = {};
  23973. var kindIndex;
  23974. var kind;
  23975. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23976. kind = kinds[kindIndex];
  23977. var vertexBuffer = this.getVertexBuffer(kind);
  23978. vbs[kind] = vertexBuffer;
  23979. data[kind] = vbs[kind].getData();
  23980. newdata[kind] = [];
  23981. }
  23982. // Save previous submeshes
  23983. var previousSubmeshes = this.subMeshes.slice(0);
  23984. var indices = this.getIndices();
  23985. var totalIndices = this.getTotalIndices();
  23986. // Generating unique vertices per face
  23987. var index;
  23988. for (index = 0; index < totalIndices; index++) {
  23989. var vertexIndex = indices[index];
  23990. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23991. kind = kinds[kindIndex];
  23992. var stride = vbs[kind].getStrideSize();
  23993. for (var offset = 0; offset < stride; offset++) {
  23994. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23995. }
  23996. }
  23997. }
  23998. // Updating indices
  23999. for (index = 0; index < totalIndices; index += 3) {
  24000. indices[index] = index;
  24001. indices[index + 1] = index + 1;
  24002. indices[index + 2] = index + 2;
  24003. }
  24004. this.setIndices(indices);
  24005. // Updating vertex buffers
  24006. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24007. kind = kinds[kindIndex];
  24008. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24009. }
  24010. // Updating submeshes
  24011. this.releaseSubMeshes();
  24012. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24013. var previousOne = previousSubmeshes[submeshIndex];
  24014. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24015. }
  24016. this._unIndexed = true;
  24017. this.synchronizeInstances();
  24018. return this;
  24019. };
  24020. /**
  24021. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24022. * This method returns the Mesh.
  24023. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24024. */
  24025. Mesh.prototype.flipFaces = function (flipNormals) {
  24026. if (flipNormals === void 0) { flipNormals = false; }
  24027. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24028. var i;
  24029. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24030. for (i = 0; i < vertex_data.normals.length; i++) {
  24031. vertex_data.normals[i] *= -1;
  24032. }
  24033. }
  24034. if (vertex_data.indices) {
  24035. var temp;
  24036. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24037. // reassign indices
  24038. temp = vertex_data.indices[i + 1];
  24039. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24040. vertex_data.indices[i + 2] = temp;
  24041. }
  24042. }
  24043. vertex_data.applyToMesh(this);
  24044. return this;
  24045. };
  24046. // Instances
  24047. /**
  24048. * Creates a new InstancedMesh object from the mesh model.
  24049. * An instance shares the same properties and the same material than its model.
  24050. * Only these properties of each instance can then be set individually :
  24051. * - position
  24052. * - rotation
  24053. * - rotationQuaternion
  24054. * - setPivotMatrix
  24055. * - scaling
  24056. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24057. * Warning : this method is not supported for Line mesh and LineSystem
  24058. */
  24059. Mesh.prototype.createInstance = function (name) {
  24060. return new BABYLON.InstancedMesh(name, this);
  24061. };
  24062. /**
  24063. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24064. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24065. * This method returns the Mesh.
  24066. */
  24067. Mesh.prototype.synchronizeInstances = function () {
  24068. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24069. var instance = this.instances[instanceIndex];
  24070. instance._syncSubMeshes();
  24071. }
  24072. return this;
  24073. };
  24074. /**
  24075. * Simplify the mesh according to the given array of settings.
  24076. * Function will return immediately and will simplify async. It returns the Mesh.
  24077. * @param settings a collection of simplification settings.
  24078. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24079. * @param type the type of simplification to run.
  24080. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24081. */
  24082. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24083. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24084. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24085. this.getScene().simplificationQueue.addTask({
  24086. settings: settings,
  24087. parallelProcessing: parallelProcessing,
  24088. mesh: this,
  24089. simplificationType: simplificationType,
  24090. successCallback: successCallback
  24091. });
  24092. return this;
  24093. };
  24094. /**
  24095. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24096. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24097. * This should be used together with the simplification to avoid disappearing triangles.
  24098. * Returns the Mesh.
  24099. * @param successCallback an optional success callback to be called after the optimization finished.
  24100. */
  24101. Mesh.prototype.optimizeIndices = function (successCallback) {
  24102. var _this = this;
  24103. var indices = this.getIndices();
  24104. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24105. if (!positions || !indices) {
  24106. return this;
  24107. }
  24108. var vectorPositions = new Array();
  24109. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24110. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24111. }
  24112. var dupes = new Array();
  24113. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24114. var realPos = vectorPositions.length - 1 - iteration;
  24115. var testedPosition = vectorPositions[realPos];
  24116. for (var j = 0; j < realPos; ++j) {
  24117. var againstPosition = vectorPositions[j];
  24118. if (testedPosition.equals(againstPosition)) {
  24119. dupes[realPos] = j;
  24120. break;
  24121. }
  24122. }
  24123. }, function () {
  24124. for (var i = 0; i < indices.length; ++i) {
  24125. indices[i] = dupes[indices[i]] || indices[i];
  24126. }
  24127. //indices are now reordered
  24128. var originalSubMeshes = _this.subMeshes.slice(0);
  24129. _this.setIndices(indices);
  24130. _this.subMeshes = originalSubMeshes;
  24131. if (successCallback) {
  24132. successCallback(_this);
  24133. }
  24134. });
  24135. return this;
  24136. };
  24137. Mesh.prototype.serialize = function (serializationObject) {
  24138. serializationObject.name = this.name;
  24139. serializationObject.id = this.id;
  24140. serializationObject.type = this.getClassName();
  24141. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24142. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24143. }
  24144. serializationObject.position = this.position.asArray();
  24145. if (this.rotationQuaternion) {
  24146. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24147. }
  24148. else if (this.rotation) {
  24149. serializationObject.rotation = this.rotation.asArray();
  24150. }
  24151. serializationObject.scaling = this.scaling.asArray();
  24152. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24153. serializationObject.isEnabled = this.isEnabled();
  24154. serializationObject.isVisible = this.isVisible;
  24155. serializationObject.infiniteDistance = this.infiniteDistance;
  24156. serializationObject.pickable = this.isPickable;
  24157. serializationObject.receiveShadows = this.receiveShadows;
  24158. serializationObject.billboardMode = this.billboardMode;
  24159. serializationObject.visibility = this.visibility;
  24160. serializationObject.checkCollisions = this.checkCollisions;
  24161. serializationObject.isBlocker = this.isBlocker;
  24162. // Parent
  24163. if (this.parent) {
  24164. serializationObject.parentId = this.parent.id;
  24165. }
  24166. // Geometry
  24167. var geometry = this._geometry;
  24168. if (geometry) {
  24169. var geometryId = geometry.id;
  24170. serializationObject.geometryId = geometryId;
  24171. // SubMeshes
  24172. serializationObject.subMeshes = [];
  24173. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24174. var subMesh = this.subMeshes[subIndex];
  24175. serializationObject.subMeshes.push({
  24176. materialIndex: subMesh.materialIndex,
  24177. verticesStart: subMesh.verticesStart,
  24178. verticesCount: subMesh.verticesCount,
  24179. indexStart: subMesh.indexStart,
  24180. indexCount: subMesh.indexCount
  24181. });
  24182. }
  24183. }
  24184. // Material
  24185. if (this.material) {
  24186. serializationObject.materialId = this.material.id;
  24187. }
  24188. else {
  24189. this.material = null;
  24190. }
  24191. // Morph targets
  24192. if (this.morphTargetManager) {
  24193. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24194. }
  24195. // Skeleton
  24196. if (this.skeleton) {
  24197. serializationObject.skeletonId = this.skeleton.id;
  24198. }
  24199. // Physics
  24200. //TODO implement correct serialization for physics impostors.
  24201. var impostor = this.getPhysicsImpostor();
  24202. if (impostor) {
  24203. serializationObject.physicsMass = impostor.getParam("mass");
  24204. serializationObject.physicsFriction = impostor.getParam("friction");
  24205. serializationObject.physicsRestitution = impostor.getParam("mass");
  24206. serializationObject.physicsImpostor = impostor.type;
  24207. }
  24208. // Metadata
  24209. if (this.metadata) {
  24210. serializationObject.metadata = this.metadata;
  24211. }
  24212. // Instances
  24213. serializationObject.instances = [];
  24214. for (var index = 0; index < this.instances.length; index++) {
  24215. var instance = this.instances[index];
  24216. var serializationInstance = {
  24217. name: instance.name,
  24218. position: instance.position.asArray(),
  24219. scaling: instance.scaling.asArray()
  24220. };
  24221. if (instance.rotationQuaternion) {
  24222. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24223. }
  24224. else if (instance.rotation) {
  24225. serializationInstance.rotation = instance.rotation.asArray();
  24226. }
  24227. serializationObject.instances.push(serializationInstance);
  24228. // Animations
  24229. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24230. serializationInstance.ranges = instance.serializeAnimationRanges();
  24231. }
  24232. //
  24233. // Animations
  24234. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24235. serializationObject.ranges = this.serializeAnimationRanges();
  24236. // Layer mask
  24237. serializationObject.layerMask = this.layerMask;
  24238. // Alpha
  24239. serializationObject.alphaIndex = this.alphaIndex;
  24240. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24241. // Overlay
  24242. serializationObject.overlayAlpha = this.overlayAlpha;
  24243. serializationObject.overlayColor = this.overlayColor.asArray();
  24244. serializationObject.renderOverlay = this.renderOverlay;
  24245. // Fog
  24246. serializationObject.applyFog = this.applyFog;
  24247. // Action Manager
  24248. if (this.actionManager) {
  24249. serializationObject.actions = this.actionManager.serialize(this.name);
  24250. }
  24251. };
  24252. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24253. if (!this.geometry) {
  24254. return;
  24255. }
  24256. this._markSubMeshesAsAttributesDirty();
  24257. var morphTargetManager = this._morphTargetManager;
  24258. if (morphTargetManager && morphTargetManager.vertexCount) {
  24259. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24260. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24261. this.morphTargetManager = null;
  24262. return;
  24263. }
  24264. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24265. var morphTarget = morphTargetManager.getActiveTarget(index);
  24266. var positions = morphTarget.getPositions();
  24267. if (!positions) {
  24268. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24269. return;
  24270. }
  24271. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24272. var normals = morphTarget.getNormals();
  24273. if (normals) {
  24274. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24275. }
  24276. var tangents = morphTarget.getTangents();
  24277. if (tangents) {
  24278. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24279. }
  24280. }
  24281. }
  24282. else {
  24283. var index = 0;
  24284. // Positions
  24285. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24286. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24287. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24288. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24289. }
  24290. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24291. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24292. }
  24293. index++;
  24294. }
  24295. }
  24296. };
  24297. // Statics
  24298. /**
  24299. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24300. * The parameter `parsedMesh` is the mesh to be copied.
  24301. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24302. */
  24303. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24304. var mesh;
  24305. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24306. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24307. }
  24308. else {
  24309. mesh = new Mesh(parsedMesh.name, scene);
  24310. }
  24311. mesh.id = parsedMesh.id;
  24312. if (BABYLON.Tags) {
  24313. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24314. }
  24315. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24316. if (parsedMesh.metadata !== undefined) {
  24317. mesh.metadata = parsedMesh.metadata;
  24318. }
  24319. if (parsedMesh.rotationQuaternion) {
  24320. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24321. }
  24322. else if (parsedMesh.rotation) {
  24323. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24324. }
  24325. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24326. if (parsedMesh.localMatrix) {
  24327. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24328. }
  24329. else if (parsedMesh.pivotMatrix) {
  24330. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24331. }
  24332. mesh.setEnabled(parsedMesh.isEnabled);
  24333. mesh.isVisible = parsedMesh.isVisible;
  24334. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24335. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24336. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24337. if (parsedMesh.applyFog !== undefined) {
  24338. mesh.applyFog = parsedMesh.applyFog;
  24339. }
  24340. if (parsedMesh.pickable !== undefined) {
  24341. mesh.isPickable = parsedMesh.pickable;
  24342. }
  24343. if (parsedMesh.alphaIndex !== undefined) {
  24344. mesh.alphaIndex = parsedMesh.alphaIndex;
  24345. }
  24346. mesh.receiveShadows = parsedMesh.receiveShadows;
  24347. mesh.billboardMode = parsedMesh.billboardMode;
  24348. if (parsedMesh.visibility !== undefined) {
  24349. mesh.visibility = parsedMesh.visibility;
  24350. }
  24351. mesh.checkCollisions = parsedMesh.checkCollisions;
  24352. if (parsedMesh.isBlocker !== undefined) {
  24353. mesh.isBlocker = parsedMesh.isBlocker;
  24354. }
  24355. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24356. // freezeWorldMatrix
  24357. if (parsedMesh.freezeWorldMatrix) {
  24358. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24359. }
  24360. // Parent
  24361. if (parsedMesh.parentId) {
  24362. mesh._waitingParentId = parsedMesh.parentId;
  24363. }
  24364. // Actions
  24365. if (parsedMesh.actions !== undefined) {
  24366. mesh._waitingActions = parsedMesh.actions;
  24367. }
  24368. // Overlay
  24369. if (parsedMesh.overlayAlpha !== undefined) {
  24370. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24371. }
  24372. if (parsedMesh.overlayColor !== undefined) {
  24373. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24374. }
  24375. if (parsedMesh.renderOverlay !== undefined) {
  24376. mesh.renderOverlay = parsedMesh.renderOverlay;
  24377. }
  24378. // Geometry
  24379. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24380. if (parsedMesh.delayLoadingFile) {
  24381. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24382. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24383. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24384. if (parsedMesh._binaryInfo) {
  24385. mesh._binaryInfo = parsedMesh._binaryInfo;
  24386. }
  24387. mesh._delayInfo = [];
  24388. if (parsedMesh.hasUVs) {
  24389. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24390. }
  24391. if (parsedMesh.hasUVs2) {
  24392. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24393. }
  24394. if (parsedMesh.hasUVs3) {
  24395. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24396. }
  24397. if (parsedMesh.hasUVs4) {
  24398. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24399. }
  24400. if (parsedMesh.hasUVs5) {
  24401. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24402. }
  24403. if (parsedMesh.hasUVs6) {
  24404. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24405. }
  24406. if (parsedMesh.hasColors) {
  24407. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24408. }
  24409. if (parsedMesh.hasMatricesIndices) {
  24410. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24411. }
  24412. if (parsedMesh.hasMatricesWeights) {
  24413. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24414. }
  24415. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24416. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24417. mesh._checkDelayState();
  24418. }
  24419. }
  24420. else {
  24421. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24422. }
  24423. // Material
  24424. if (parsedMesh.materialId) {
  24425. mesh.setMaterialByID(parsedMesh.materialId);
  24426. }
  24427. else {
  24428. mesh.material = null;
  24429. }
  24430. // Morph targets
  24431. if (parsedMesh.morphTargetManagerId > -1) {
  24432. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24433. }
  24434. // Skeleton
  24435. if (parsedMesh.skeletonId > -1) {
  24436. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24437. if (parsedMesh.numBoneInfluencers) {
  24438. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24439. }
  24440. }
  24441. // Animations
  24442. if (parsedMesh.animations) {
  24443. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24444. var parsedAnimation = parsedMesh.animations[animationIndex];
  24445. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24446. }
  24447. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24448. }
  24449. if (parsedMesh.autoAnimate) {
  24450. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24451. }
  24452. // Layer Mask
  24453. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24454. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24455. }
  24456. else {
  24457. mesh.layerMask = 0x0FFFFFFF;
  24458. }
  24459. // Physics
  24460. if (parsedMesh.physicsImpostor) {
  24461. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24462. mass: parsedMesh.physicsMass,
  24463. friction: parsedMesh.physicsFriction,
  24464. restitution: parsedMesh.physicsRestitution
  24465. }, scene);
  24466. }
  24467. // Instances
  24468. if (parsedMesh.instances) {
  24469. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24470. var parsedInstance = parsedMesh.instances[index];
  24471. var instance = mesh.createInstance(parsedInstance.name);
  24472. if (BABYLON.Tags) {
  24473. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24474. }
  24475. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24476. if (parsedInstance.parentId) {
  24477. instance._waitingParentId = parsedInstance.parentId;
  24478. }
  24479. if (parsedInstance.rotationQuaternion) {
  24480. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24481. }
  24482. else if (parsedInstance.rotation) {
  24483. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24484. }
  24485. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24486. instance.checkCollisions = mesh.checkCollisions;
  24487. if (parsedMesh.animations) {
  24488. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24489. parsedAnimation = parsedMesh.animations[animationIndex];
  24490. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24491. }
  24492. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24493. }
  24494. }
  24495. }
  24496. return mesh;
  24497. };
  24498. /**
  24499. * Creates a ribbon mesh.
  24500. * Please consider using the same method from the MeshBuilder class instead.
  24501. * 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.
  24502. *
  24503. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24504. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24505. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24506. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24507. * 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.
  24508. * 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.
  24509. * 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
  24510. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24511. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24513. */
  24514. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24515. if (closeArray === void 0) { closeArray = false; }
  24516. if (updatable === void 0) { updatable = false; }
  24517. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24518. pathArray: pathArray,
  24519. closeArray: closeArray,
  24520. closePath: closePath,
  24521. offset: offset,
  24522. updatable: updatable,
  24523. sideOrientation: sideOrientation,
  24524. instance: instance
  24525. }, scene);
  24526. };
  24527. /**
  24528. * Creates a plane polygonal mesh. By default, this is a disc.
  24529. * Please consider using the same method from the MeshBuilder class instead.
  24530. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24531. * 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.
  24532. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24533. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24535. */
  24536. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24537. if (scene === void 0) { scene = null; }
  24538. var options = {
  24539. radius: radius,
  24540. tessellation: tessellation,
  24541. sideOrientation: sideOrientation,
  24542. updatable: updatable
  24543. };
  24544. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24545. };
  24546. /**
  24547. * Creates a box mesh.
  24548. * Please consider using the same method from the MeshBuilder class instead.
  24549. * The parameter `size` sets the size (float) of each box side (default 1).
  24550. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24551. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24553. */
  24554. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24555. if (scene === void 0) { scene = null; }
  24556. var options = {
  24557. size: size,
  24558. sideOrientation: sideOrientation,
  24559. updatable: updatable
  24560. };
  24561. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24562. };
  24563. /**
  24564. * Creates a sphere mesh.
  24565. * Please consider using the same method from the MeshBuilder class instead.
  24566. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24567. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24568. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24569. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24570. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24571. */
  24572. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24573. var options = {
  24574. segments: segments,
  24575. diameterX: diameter,
  24576. diameterY: diameter,
  24577. diameterZ: diameter,
  24578. sideOrientation: sideOrientation,
  24579. updatable: updatable
  24580. };
  24581. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24582. };
  24583. /**
  24584. * Creates a cylinder or a cone mesh.
  24585. * Please consider using the same method from the MeshBuilder class instead.
  24586. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24587. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24588. * 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.
  24589. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24590. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24591. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24592. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24593. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24594. */
  24595. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24596. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24597. if (scene !== undefined) {
  24598. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24599. updatable = scene;
  24600. }
  24601. scene = subdivisions;
  24602. subdivisions = 1;
  24603. }
  24604. var options = {
  24605. height: height,
  24606. diameterTop: diameterTop,
  24607. diameterBottom: diameterBottom,
  24608. tessellation: tessellation,
  24609. subdivisions: subdivisions,
  24610. sideOrientation: sideOrientation,
  24611. updatable: updatable
  24612. };
  24613. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24614. };
  24615. // Torus (Code from SharpDX.org)
  24616. /**
  24617. * Creates a torus mesh.
  24618. * Please consider using the same method from the MeshBuilder class instead.
  24619. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24620. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24621. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24622. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24623. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24624. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24625. */
  24626. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24627. var options = {
  24628. diameter: diameter,
  24629. thickness: thickness,
  24630. tessellation: tessellation,
  24631. sideOrientation: sideOrientation,
  24632. updatable: updatable
  24633. };
  24634. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24635. };
  24636. /**
  24637. * Creates a torus knot mesh.
  24638. * Please consider using the same method from the MeshBuilder class instead.
  24639. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24640. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24641. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24642. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24643. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24644. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24645. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24646. */
  24647. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24648. var options = {
  24649. radius: radius,
  24650. tube: tube,
  24651. radialSegments: radialSegments,
  24652. tubularSegments: tubularSegments,
  24653. p: p,
  24654. q: q,
  24655. sideOrientation: sideOrientation,
  24656. updatable: updatable
  24657. };
  24658. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24659. };
  24660. /**
  24661. * Creates a line mesh.
  24662. * Please consider using the same method from the MeshBuilder class instead.
  24663. * 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.
  24664. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24665. * The parameter `points` is an array successive Vector3.
  24666. * 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
  24667. * When updating an instance, remember that only point positions can change, not the number of points.
  24668. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24669. */
  24670. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24671. if (scene === void 0) { scene = null; }
  24672. if (updatable === void 0) { updatable = false; }
  24673. if (instance === void 0) { instance = null; }
  24674. var options = {
  24675. points: points,
  24676. updatable: updatable,
  24677. instance: instance
  24678. };
  24679. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24680. };
  24681. /**
  24682. * Creates a dashed line mesh.
  24683. * Please consider using the same method from the MeshBuilder class instead.
  24684. * 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.
  24685. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24686. * The parameter `points` is an array successive Vector3.
  24687. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24688. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24689. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24690. * 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
  24691. * When updating an instance, remember that only point positions can change, not the number of points.
  24692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24693. */
  24694. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24695. if (scene === void 0) { scene = null; }
  24696. var options = {
  24697. points: points,
  24698. dashSize: dashSize,
  24699. gapSize: gapSize,
  24700. dashNb: dashNb,
  24701. updatable: updatable,
  24702. instance: instance
  24703. };
  24704. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24705. };
  24706. /**
  24707. * Creates a polygon mesh.
  24708. * Please consider using the same method from the MeshBuilder class instead.
  24709. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  24710. * 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.
  24711. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24713. * Remember you can only change the shape positions, not their number when updating a polygon.
  24714. */
  24715. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  24716. var options = {
  24717. shape: shape,
  24718. holes: holes,
  24719. updatable: updatable,
  24720. sideOrientation: sideOrientation
  24721. };
  24722. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  24723. };
  24724. /**
  24725. * Creates an extruded polygon mesh, with depth in the Y direction.
  24726. * Please consider using the same method from the MeshBuilder class instead.
  24727. */
  24728. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  24729. var options = {
  24730. shape: shape,
  24731. holes: holes,
  24732. depth: depth,
  24733. updatable: updatable,
  24734. sideOrientation: sideOrientation
  24735. };
  24736. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  24737. };
  24738. /**
  24739. * Creates an extruded shape mesh.
  24740. * 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.
  24741. * Please consider using the same method from the MeshBuilder class instead.
  24742. *
  24743. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24744. * 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
  24745. * extruded along the Z axis.
  24746. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24747. * 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.
  24748. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24749. * 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
  24750. * 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
  24751. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24752. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24753. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24754. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24755. */
  24756. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24757. if (scene === void 0) { scene = null; }
  24758. var options = {
  24759. shape: shape,
  24760. path: path,
  24761. scale: scale,
  24762. rotation: rotation,
  24763. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24764. sideOrientation: sideOrientation,
  24765. instance: instance,
  24766. updatable: updatable
  24767. };
  24768. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24769. };
  24770. /**
  24771. * Creates an custom extruded shape mesh.
  24772. * 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.
  24773. * Please consider using the same method from the MeshBuilder class instead.
  24774. *
  24775. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24776. * 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
  24777. * extruded along the Z axis.
  24778. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24779. * 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
  24780. * and the distance of this point from the begining of the path :
  24781. * ```javascript
  24782. * var rotationFunction = function(i, distance) {
  24783. * // do things
  24784. * return rotationValue; }
  24785. * ```
  24786. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24787. * 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
  24788. * and the distance of this point from the begining of the path :
  24789. * ```javascript
  24790. * var scaleFunction = function(i, distance) {
  24791. * // do things
  24792. * return scaleValue;}
  24793. * ```
  24794. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24795. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24796. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24797. * 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
  24798. * 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
  24799. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24800. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24801. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24802. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24803. */
  24804. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24805. var options = {
  24806. shape: shape,
  24807. path: path,
  24808. scaleFunction: scaleFunction,
  24809. rotationFunction: rotationFunction,
  24810. ribbonCloseArray: ribbonCloseArray,
  24811. ribbonClosePath: ribbonClosePath,
  24812. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24813. sideOrientation: sideOrientation,
  24814. instance: instance,
  24815. updatable: updatable
  24816. };
  24817. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24818. };
  24819. /**
  24820. * Creates lathe mesh.
  24821. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24822. * Please consider using the same method from the MeshBuilder class instead.
  24823. * 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
  24824. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24825. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24826. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24827. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24828. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24829. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24830. */
  24831. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24832. var options = {
  24833. shape: shape,
  24834. radius: radius,
  24835. tessellation: tessellation,
  24836. sideOrientation: sideOrientation,
  24837. updatable: updatable
  24838. };
  24839. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24840. };
  24841. /**
  24842. * Creates a plane mesh.
  24843. * Please consider using the same method from the MeshBuilder class instead.
  24844. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24845. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24846. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24847. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24848. */
  24849. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24850. var options = {
  24851. size: size,
  24852. width: size,
  24853. height: size,
  24854. sideOrientation: sideOrientation,
  24855. updatable: updatable
  24856. };
  24857. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24858. };
  24859. /**
  24860. * Creates a ground mesh.
  24861. * Please consider using the same method from the MeshBuilder class instead.
  24862. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24863. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24864. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24865. */
  24866. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24867. var options = {
  24868. width: width,
  24869. height: height,
  24870. subdivisions: subdivisions,
  24871. updatable: updatable
  24872. };
  24873. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24874. };
  24875. /**
  24876. * Creates a tiled ground mesh.
  24877. * Please consider using the same method from the MeshBuilder class instead.
  24878. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24879. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24880. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24881. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24882. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24883. * numbers of subdivisions on the ground width and height of each tile.
  24884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24885. */
  24886. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24887. var options = {
  24888. xmin: xmin,
  24889. zmin: zmin,
  24890. xmax: xmax,
  24891. zmax: zmax,
  24892. subdivisions: subdivisions,
  24893. precision: precision,
  24894. updatable: updatable
  24895. };
  24896. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24897. };
  24898. /**
  24899. * Creates a ground mesh from a height map.
  24900. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24901. * Please consider using the same method from the MeshBuilder class instead.
  24902. * The parameter `url` sets the URL of the height map image resource.
  24903. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24904. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24905. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24906. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24907. * 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).
  24908. * This function is passed the newly built mesh :
  24909. * ```javascript
  24910. * function(mesh) { // do things
  24911. * return; }
  24912. * ```
  24913. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24914. */
  24915. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24916. var options = {
  24917. width: width,
  24918. height: height,
  24919. subdivisions: subdivisions,
  24920. minHeight: minHeight,
  24921. maxHeight: maxHeight,
  24922. updatable: updatable,
  24923. onReady: onReady
  24924. };
  24925. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24926. };
  24927. /**
  24928. * Creates a tube mesh.
  24929. * 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.
  24930. * Please consider using the same method from the MeshBuilder class instead.
  24931. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24932. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24933. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24934. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24935. * 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.
  24936. * It must return a radius value (positive float) :
  24937. * ```javascript
  24938. * var radiusFunction = function(i, distance) {
  24939. * // do things
  24940. * return radius; }
  24941. * ```
  24942. * 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
  24943. * 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
  24944. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24945. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24946. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24947. */
  24948. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24949. var options = {
  24950. path: path,
  24951. radius: radius,
  24952. tessellation: tessellation,
  24953. radiusFunction: radiusFunction,
  24954. arc: 1,
  24955. cap: cap,
  24956. updatable: updatable,
  24957. sideOrientation: sideOrientation,
  24958. instance: instance
  24959. };
  24960. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24961. };
  24962. /**
  24963. * Creates a polyhedron mesh.
  24964. * Please consider using the same method from the MeshBuilder class instead.
  24965. * 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
  24966. * to choose the wanted type.
  24967. * The parameter `size` (positive float, default 1) sets the polygon size.
  24968. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24969. * 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`.
  24970. * 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
  24971. * 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)`).
  24972. * 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
  24973. * 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.
  24974. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24975. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24976. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24977. */
  24978. Mesh.CreatePolyhedron = function (name, options, scene) {
  24979. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24980. };
  24981. /**
  24982. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24983. * Please consider using the same method from the MeshBuilder class instead.
  24984. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24985. * 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`).
  24986. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24987. * 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.
  24988. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24989. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24991. */
  24992. Mesh.CreateIcoSphere = function (name, options, scene) {
  24993. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24994. };
  24995. /**
  24996. * Creates a decal mesh.
  24997. * Please consider using the same method from the MeshBuilder class instead.
  24998. * 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.
  24999. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25000. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25001. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25002. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25003. */
  25004. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25005. var options = {
  25006. position: position,
  25007. normal: normal,
  25008. size: size,
  25009. angle: angle
  25010. };
  25011. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25012. };
  25013. // Skeletons
  25014. /**
  25015. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25016. */
  25017. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25018. if (!this._sourcePositions) {
  25019. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25020. if (!source) {
  25021. return this._sourcePositions;
  25022. }
  25023. this._sourcePositions = new Float32Array(source);
  25024. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25025. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25026. }
  25027. }
  25028. return this._sourcePositions;
  25029. };
  25030. /**
  25031. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25032. */
  25033. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25034. if (!this._sourceNormals) {
  25035. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25036. if (!source) {
  25037. return this._sourceNormals;
  25038. }
  25039. this._sourceNormals = new Float32Array(source);
  25040. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25041. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25042. }
  25043. }
  25044. return this._sourceNormals;
  25045. };
  25046. /**
  25047. * Updates the vertex buffer by applying transformation from the bones.
  25048. * Returns the Mesh.
  25049. *
  25050. * @param {skeleton} skeleton to apply
  25051. */
  25052. Mesh.prototype.applySkeleton = function (skeleton) {
  25053. if (!this.geometry) {
  25054. return this;
  25055. }
  25056. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25057. return this;
  25058. }
  25059. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25060. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25061. return this;
  25062. }
  25063. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25064. return this;
  25065. }
  25066. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25067. return this;
  25068. }
  25069. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25070. return this;
  25071. }
  25072. if (!this._sourcePositions) {
  25073. var submeshes = this.subMeshes.slice();
  25074. this.setPositionsForCPUSkinning();
  25075. this.subMeshes = submeshes;
  25076. }
  25077. if (!this._sourceNormals) {
  25078. this.setNormalsForCPUSkinning();
  25079. }
  25080. // positionsData checks for not being Float32Array will only pass at most once
  25081. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25082. if (!positionsData) {
  25083. return this;
  25084. }
  25085. if (!(positionsData instanceof Float32Array)) {
  25086. positionsData = new Float32Array(positionsData);
  25087. }
  25088. // normalsData checks for not being Float32Array will only pass at most once
  25089. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25090. if (!normalsData) {
  25091. return this;
  25092. }
  25093. if (!(normalsData instanceof Float32Array)) {
  25094. normalsData = new Float32Array(normalsData);
  25095. }
  25096. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25097. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25098. if (!matricesWeightsData || !matricesIndicesData) {
  25099. return this;
  25100. }
  25101. var needExtras = this.numBoneInfluencers > 4;
  25102. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25103. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25104. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  25105. return this;
  25106. }
  25107. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25108. var tempVector3 = BABYLON.Vector3.Zero();
  25109. var finalMatrix = new BABYLON.Matrix();
  25110. var tempMatrix = new BABYLON.Matrix();
  25111. var matWeightIdx = 0;
  25112. var inf;
  25113. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25114. var weight;
  25115. for (inf = 0; inf < 4; inf++) {
  25116. weight = matricesWeightsData[matWeightIdx + inf];
  25117. if (weight > 0) {
  25118. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25119. finalMatrix.addToSelf(tempMatrix);
  25120. }
  25121. else
  25122. break;
  25123. }
  25124. if (needExtras) {
  25125. for (inf = 0; inf < 4; inf++) {
  25126. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25127. if (weight > 0) {
  25128. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25129. finalMatrix.addToSelf(tempMatrix);
  25130. }
  25131. else
  25132. break;
  25133. }
  25134. }
  25135. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25136. tempVector3.toArray(positionsData, index);
  25137. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25138. tempVector3.toArray(normalsData, index);
  25139. finalMatrix.reset();
  25140. }
  25141. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25142. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25143. return this;
  25144. };
  25145. // Tools
  25146. /**
  25147. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25148. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25149. */
  25150. Mesh.MinMax = function (meshes) {
  25151. var minVector = null;
  25152. var maxVector = null;
  25153. meshes.forEach(function (mesh, index, array) {
  25154. var boundingInfo = mesh.getBoundingInfo();
  25155. if (!boundingInfo) {
  25156. return;
  25157. }
  25158. var boundingBox = boundingInfo.boundingBox;
  25159. if (!minVector || !maxVector) {
  25160. minVector = boundingBox.minimumWorld;
  25161. maxVector = boundingBox.maximumWorld;
  25162. }
  25163. else {
  25164. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25165. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25166. }
  25167. });
  25168. if (!minVector || !maxVector) {
  25169. return {
  25170. min: BABYLON.Vector3.Zero(),
  25171. max: BABYLON.Vector3.Zero()
  25172. };
  25173. }
  25174. return {
  25175. min: minVector,
  25176. max: maxVector
  25177. };
  25178. };
  25179. /**
  25180. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25181. */
  25182. Mesh.Center = function (meshesOrMinMaxVector) {
  25183. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25184. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25185. };
  25186. /**
  25187. * Merge the array of meshes into a single mesh for performance reasons.
  25188. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25189. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25190. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25191. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25192. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25193. */
  25194. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25195. if (disposeSource === void 0) { disposeSource = true; }
  25196. var index;
  25197. if (!allow32BitsIndices) {
  25198. var totalVertices = 0;
  25199. // Counting vertices
  25200. for (index = 0; index < meshes.length; index++) {
  25201. if (meshes[index]) {
  25202. totalVertices += meshes[index].getTotalVertices();
  25203. if (totalVertices > 65536) {
  25204. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25205. return null;
  25206. }
  25207. }
  25208. }
  25209. }
  25210. // Merge
  25211. var vertexData = null;
  25212. var otherVertexData;
  25213. var indiceArray = new Array();
  25214. var source = null;
  25215. for (index = 0; index < meshes.length; index++) {
  25216. if (meshes[index]) {
  25217. meshes[index].computeWorldMatrix(true);
  25218. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25219. otherVertexData.transform(meshes[index].getWorldMatrix());
  25220. if (vertexData) {
  25221. vertexData.merge(otherVertexData);
  25222. }
  25223. else {
  25224. vertexData = otherVertexData;
  25225. source = meshes[index];
  25226. }
  25227. if (subdivideWithSubMeshes) {
  25228. indiceArray.push(meshes[index].getTotalIndices());
  25229. }
  25230. }
  25231. }
  25232. source = source;
  25233. if (!meshSubclass) {
  25234. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25235. }
  25236. vertexData.applyToMesh(meshSubclass);
  25237. // Setting properties
  25238. meshSubclass.material = source.material;
  25239. meshSubclass.checkCollisions = source.checkCollisions;
  25240. // Cleaning
  25241. if (disposeSource) {
  25242. for (index = 0; index < meshes.length; index++) {
  25243. if (meshes[index]) {
  25244. meshes[index].dispose();
  25245. }
  25246. }
  25247. }
  25248. // Subdivide
  25249. if (subdivideWithSubMeshes) {
  25250. //-- Suppresions du submesh global
  25251. meshSubclass.releaseSubMeshes();
  25252. index = 0;
  25253. var offset = 0;
  25254. //-- aplique la subdivision en fonction du tableau d'indices
  25255. while (index < indiceArray.length) {
  25256. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25257. offset += indiceArray[index];
  25258. index++;
  25259. }
  25260. }
  25261. return meshSubclass;
  25262. };
  25263. // Consts
  25264. Mesh._FRONTSIDE = 0;
  25265. Mesh._BACKSIDE = 1;
  25266. Mesh._DOUBLESIDE = 2;
  25267. Mesh._DEFAULTSIDE = 0;
  25268. Mesh._NO_CAP = 0;
  25269. Mesh._CAP_START = 1;
  25270. Mesh._CAP_END = 2;
  25271. Mesh._CAP_ALL = 3;
  25272. return Mesh;
  25273. }(BABYLON.AbstractMesh));
  25274. BABYLON.Mesh = Mesh;
  25275. })(BABYLON || (BABYLON = {}));
  25276. //# sourceMappingURL=babylon.mesh.js.map
  25277. var BABYLON;
  25278. (function (BABYLON) {
  25279. var BaseSubMesh = /** @class */ (function () {
  25280. function BaseSubMesh() {
  25281. }
  25282. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25283. get: function () {
  25284. return this._materialEffect;
  25285. },
  25286. enumerable: true,
  25287. configurable: true
  25288. });
  25289. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25290. if (defines === void 0) { defines = null; }
  25291. if (this._materialEffect === effect) {
  25292. if (!effect) {
  25293. this._materialDefines = null;
  25294. }
  25295. return;
  25296. }
  25297. this._materialDefines = defines;
  25298. this._materialEffect = effect;
  25299. };
  25300. return BaseSubMesh;
  25301. }());
  25302. BABYLON.BaseSubMesh = BaseSubMesh;
  25303. var SubMesh = /** @class */ (function (_super) {
  25304. __extends(SubMesh, _super);
  25305. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25306. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25307. var _this = _super.call(this) || this;
  25308. _this.materialIndex = materialIndex;
  25309. _this.verticesStart = verticesStart;
  25310. _this.verticesCount = verticesCount;
  25311. _this.indexStart = indexStart;
  25312. _this.indexCount = indexCount;
  25313. _this._renderId = 0;
  25314. _this._mesh = mesh;
  25315. _this._renderingMesh = renderingMesh || mesh;
  25316. mesh.subMeshes.push(_this);
  25317. _this._trianglePlanes = [];
  25318. _this._id = mesh.subMeshes.length - 1;
  25319. if (createBoundingBox) {
  25320. _this.refreshBoundingInfo();
  25321. mesh.computeWorldMatrix(true);
  25322. }
  25323. return _this;
  25324. }
  25325. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25326. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25327. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25328. };
  25329. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25330. get: function () {
  25331. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25332. },
  25333. enumerable: true,
  25334. configurable: true
  25335. });
  25336. /**
  25337. * Returns the submesh BoudingInfo object.
  25338. */
  25339. SubMesh.prototype.getBoundingInfo = function () {
  25340. if (this.IsGlobal) {
  25341. return this._mesh.getBoundingInfo();
  25342. }
  25343. return this._boundingInfo;
  25344. };
  25345. /**
  25346. * Sets the submesh BoundingInfo.
  25347. * Return the SubMesh.
  25348. */
  25349. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25350. this._boundingInfo = boundingInfo;
  25351. return this;
  25352. };
  25353. /**
  25354. * Returns the mesh of the current submesh.
  25355. */
  25356. SubMesh.prototype.getMesh = function () {
  25357. return this._mesh;
  25358. };
  25359. /**
  25360. * Returns the rendering mesh of the submesh.
  25361. */
  25362. SubMesh.prototype.getRenderingMesh = function () {
  25363. return this._renderingMesh;
  25364. };
  25365. /**
  25366. * Returns the submesh material.
  25367. */
  25368. SubMesh.prototype.getMaterial = function () {
  25369. var rootMaterial = this._renderingMesh.material;
  25370. if (rootMaterial && rootMaterial.getSubMaterial) {
  25371. var multiMaterial = rootMaterial;
  25372. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25373. if (this._currentMaterial !== effectiveMaterial) {
  25374. this._currentMaterial = effectiveMaterial;
  25375. this._materialDefines = null;
  25376. }
  25377. return effectiveMaterial;
  25378. }
  25379. if (!rootMaterial) {
  25380. return this._mesh.getScene().defaultMaterial;
  25381. }
  25382. return rootMaterial;
  25383. };
  25384. // Methods
  25385. /**
  25386. * Sets a new updated BoundingInfo object to the submesh.
  25387. * Returns the SubMesh.
  25388. */
  25389. SubMesh.prototype.refreshBoundingInfo = function () {
  25390. this._lastColliderWorldVertices = null;
  25391. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25392. return this;
  25393. }
  25394. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25395. if (!data) {
  25396. this._boundingInfo = this._mesh._boundingInfo;
  25397. return this;
  25398. }
  25399. var indices = this._renderingMesh.getIndices();
  25400. var extend;
  25401. //is this the only submesh?
  25402. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25403. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25404. if (!boundingInfo) {
  25405. return this;
  25406. }
  25407. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25408. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25409. }
  25410. else {
  25411. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25412. }
  25413. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25414. return this;
  25415. };
  25416. SubMesh.prototype._checkCollision = function (collider) {
  25417. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25418. if (!boundingInfo) {
  25419. return false;
  25420. }
  25421. return boundingInfo._checkCollision(collider);
  25422. };
  25423. /**
  25424. * Updates the submesh BoundingInfo.
  25425. * Returns the Submesh.
  25426. */
  25427. SubMesh.prototype.updateBoundingInfo = function (world) {
  25428. var boundingInfo = this.getBoundingInfo();
  25429. if (!boundingInfo) {
  25430. this.refreshBoundingInfo();
  25431. }
  25432. boundingInfo.update(world);
  25433. return this;
  25434. };
  25435. /**
  25436. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25437. * Boolean returned.
  25438. */
  25439. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25440. var boundingInfo = this.getBoundingInfo();
  25441. if (!boundingInfo) {
  25442. return false;
  25443. }
  25444. return boundingInfo.isInFrustum(frustumPlanes);
  25445. };
  25446. /**
  25447. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25448. * Boolean returned.
  25449. */
  25450. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25451. var boundingInfo = this.getBoundingInfo();
  25452. if (!boundingInfo) {
  25453. return false;
  25454. }
  25455. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25456. };
  25457. /**
  25458. * Renders the submesh.
  25459. * Returns it.
  25460. */
  25461. SubMesh.prototype.render = function (enableAlphaMode) {
  25462. this._renderingMesh.render(this, enableAlphaMode);
  25463. return this;
  25464. };
  25465. /**
  25466. * Returns a new Index Buffer.
  25467. * Type returned : WebGLBuffer.
  25468. */
  25469. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25470. if (!this._linesIndexBuffer) {
  25471. var linesIndices = [];
  25472. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25473. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25474. }
  25475. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25476. this.linesIndexCount = linesIndices.length;
  25477. }
  25478. return this._linesIndexBuffer;
  25479. };
  25480. /**
  25481. * True is the passed Ray intersects the submesh bounding box.
  25482. * Boolean returned.
  25483. */
  25484. SubMesh.prototype.canIntersects = function (ray) {
  25485. var boundingInfo = this.getBoundingInfo();
  25486. if (!boundingInfo) {
  25487. return false;
  25488. }
  25489. return ray.intersectsBox(boundingInfo.boundingBox);
  25490. };
  25491. /**
  25492. * Returns an object IntersectionInfo.
  25493. */
  25494. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25495. var intersectInfo = null;
  25496. // LineMesh first as it's also a Mesh...
  25497. if (this._mesh instanceof BABYLON.LinesMesh) {
  25498. var lineMesh = this._mesh;
  25499. // Line test
  25500. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25501. var p0 = positions[indices[index]];
  25502. var p1 = positions[indices[index + 1]];
  25503. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25504. if (length < 0) {
  25505. continue;
  25506. }
  25507. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25508. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25509. if (fastCheck) {
  25510. break;
  25511. }
  25512. }
  25513. }
  25514. }
  25515. else {
  25516. // Triangles test
  25517. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25518. var p0 = positions[indices[index]];
  25519. var p1 = positions[indices[index + 1]];
  25520. var p2 = positions[indices[index + 2]];
  25521. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25522. if (currentIntersectInfo) {
  25523. if (currentIntersectInfo.distance < 0) {
  25524. continue;
  25525. }
  25526. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25527. intersectInfo = currentIntersectInfo;
  25528. intersectInfo.faceId = index / 3;
  25529. if (fastCheck) {
  25530. break;
  25531. }
  25532. }
  25533. }
  25534. }
  25535. }
  25536. return intersectInfo;
  25537. };
  25538. SubMesh.prototype._rebuild = function () {
  25539. if (this._linesIndexBuffer) {
  25540. this._linesIndexBuffer = null;
  25541. }
  25542. };
  25543. // Clone
  25544. /**
  25545. * Creates a new Submesh from the passed Mesh.
  25546. */
  25547. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25548. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25549. if (!this.IsGlobal) {
  25550. var boundingInfo = this.getBoundingInfo();
  25551. if (!boundingInfo) {
  25552. return result;
  25553. }
  25554. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  25555. }
  25556. return result;
  25557. };
  25558. // Dispose
  25559. /**
  25560. * Disposes the Submesh.
  25561. * Returns nothing.
  25562. */
  25563. SubMesh.prototype.dispose = function () {
  25564. if (this._linesIndexBuffer) {
  25565. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25566. this._linesIndexBuffer = null;
  25567. }
  25568. // Remove from mesh
  25569. var index = this._mesh.subMeshes.indexOf(this);
  25570. this._mesh.subMeshes.splice(index, 1);
  25571. };
  25572. // Statics
  25573. /**
  25574. * Creates a new Submesh from the passed parameters :
  25575. * - materialIndex (integer) : the index of the main mesh material.
  25576. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25577. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25578. * - mesh (Mesh) : the main mesh to create the submesh from.
  25579. * - renderingMesh (optional Mesh) : rendering mesh.
  25580. */
  25581. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25582. var minVertexIndex = Number.MAX_VALUE;
  25583. var maxVertexIndex = -Number.MAX_VALUE;
  25584. renderingMesh = (renderingMesh || mesh);
  25585. var indices = renderingMesh.getIndices();
  25586. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25587. var vertexIndex = indices[index];
  25588. if (vertexIndex < minVertexIndex)
  25589. minVertexIndex = vertexIndex;
  25590. if (vertexIndex > maxVertexIndex)
  25591. maxVertexIndex = vertexIndex;
  25592. }
  25593. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25594. };
  25595. return SubMesh;
  25596. }(BaseSubMesh));
  25597. BABYLON.SubMesh = SubMesh;
  25598. })(BABYLON || (BABYLON = {}));
  25599. //# sourceMappingURL=babylon.subMesh.js.map
  25600. var BABYLON;
  25601. (function (BABYLON) {
  25602. var EffectFallbacks = /** @class */ (function () {
  25603. function EffectFallbacks() {
  25604. this._defines = {};
  25605. this._currentRank = 32;
  25606. this._maxRank = -1;
  25607. }
  25608. EffectFallbacks.prototype.unBindMesh = function () {
  25609. this._mesh = null;
  25610. };
  25611. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25612. if (!this._defines[rank]) {
  25613. if (rank < this._currentRank) {
  25614. this._currentRank = rank;
  25615. }
  25616. if (rank > this._maxRank) {
  25617. this._maxRank = rank;
  25618. }
  25619. this._defines[rank] = new Array();
  25620. }
  25621. this._defines[rank].push(define);
  25622. };
  25623. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25624. this._meshRank = rank;
  25625. this._mesh = mesh;
  25626. if (rank < this._currentRank) {
  25627. this._currentRank = rank;
  25628. }
  25629. if (rank > this._maxRank) {
  25630. this._maxRank = rank;
  25631. }
  25632. };
  25633. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25634. get: function () {
  25635. return this._currentRank <= this._maxRank;
  25636. },
  25637. enumerable: true,
  25638. configurable: true
  25639. });
  25640. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25641. // First we try to switch to CPU skinning
  25642. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  25643. this._mesh.computeBonesUsingShaders = false;
  25644. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25645. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25646. var scene = this._mesh.getScene();
  25647. for (var index = 0; index < scene.meshes.length; index++) {
  25648. var otherMesh = scene.meshes[index];
  25649. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  25650. otherMesh.computeBonesUsingShaders = false;
  25651. }
  25652. }
  25653. }
  25654. else {
  25655. var currentFallbacks = this._defines[this._currentRank];
  25656. if (currentFallbacks) {
  25657. for (var index = 0; index < currentFallbacks.length; index++) {
  25658. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25659. }
  25660. }
  25661. this._currentRank++;
  25662. }
  25663. return currentDefines;
  25664. };
  25665. return EffectFallbacks;
  25666. }());
  25667. BABYLON.EffectFallbacks = EffectFallbacks;
  25668. var EffectCreationOptions = /** @class */ (function () {
  25669. function EffectCreationOptions() {
  25670. }
  25671. return EffectCreationOptions;
  25672. }());
  25673. BABYLON.EffectCreationOptions = EffectCreationOptions;
  25674. var Effect = /** @class */ (function () {
  25675. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25676. if (samplers === void 0) { samplers = null; }
  25677. if (defines === void 0) { defines = null; }
  25678. if (fallbacks === void 0) { fallbacks = null; }
  25679. if (onCompiled === void 0) { onCompiled = null; }
  25680. if (onError === void 0) { onError = null; }
  25681. var _this = this;
  25682. this.uniqueId = 0;
  25683. this.onCompileObservable = new BABYLON.Observable();
  25684. this.onErrorObservable = new BABYLON.Observable();
  25685. this.onBindObservable = new BABYLON.Observable();
  25686. this._uniformBuffersNames = {};
  25687. this._isReady = false;
  25688. this._compilationError = "";
  25689. this.name = baseName;
  25690. if (attributesNamesOrOptions.attributes) {
  25691. var options = attributesNamesOrOptions;
  25692. this._engine = uniformsNamesOrEngine;
  25693. this._attributesNames = options.attributes;
  25694. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  25695. this._samplers = options.samplers;
  25696. this.defines = options.defines;
  25697. this.onError = options.onError;
  25698. this.onCompiled = options.onCompiled;
  25699. this._fallbacks = options.fallbacks;
  25700. this._indexParameters = options.indexParameters;
  25701. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  25702. if (options.uniformBuffersNames) {
  25703. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  25704. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  25705. }
  25706. }
  25707. }
  25708. else {
  25709. this._engine = engine;
  25710. this.defines = defines;
  25711. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  25712. this._samplers = samplers;
  25713. this._attributesNames = attributesNamesOrOptions;
  25714. this.onError = onError;
  25715. this.onCompiled = onCompiled;
  25716. this._indexParameters = indexParameters;
  25717. this._fallbacks = fallbacks;
  25718. }
  25719. this.uniqueId = Effect._uniqueIdSeed++;
  25720. var vertexSource;
  25721. var fragmentSource;
  25722. if (baseName.vertexElement) {
  25723. vertexSource = document.getElementById(baseName.vertexElement);
  25724. if (!vertexSource) {
  25725. vertexSource = baseName.vertexElement;
  25726. }
  25727. }
  25728. else {
  25729. vertexSource = baseName.vertex || baseName;
  25730. }
  25731. if (baseName.fragmentElement) {
  25732. fragmentSource = document.getElementById(baseName.fragmentElement);
  25733. if (!fragmentSource) {
  25734. fragmentSource = baseName.fragmentElement;
  25735. }
  25736. }
  25737. else {
  25738. fragmentSource = baseName.fragment || baseName;
  25739. }
  25740. this._loadVertexShader(vertexSource, function (vertexCode) {
  25741. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25742. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25743. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25744. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25745. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25746. if (baseName) {
  25747. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  25748. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  25749. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  25750. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  25751. }
  25752. else {
  25753. _this._vertexSourceCode = migratedVertexCode;
  25754. _this._fragmentSourceCode = migratedFragmentCode;
  25755. }
  25756. _this._prepareEffect();
  25757. });
  25758. });
  25759. });
  25760. });
  25761. });
  25762. });
  25763. }
  25764. Object.defineProperty(Effect.prototype, "key", {
  25765. get: function () {
  25766. return this._key;
  25767. },
  25768. enumerable: true,
  25769. configurable: true
  25770. });
  25771. // Properties
  25772. Effect.prototype.isReady = function () {
  25773. return this._isReady;
  25774. };
  25775. Effect.prototype.getEngine = function () {
  25776. return this._engine;
  25777. };
  25778. Effect.prototype.getProgram = function () {
  25779. return this._program;
  25780. };
  25781. Effect.prototype.getAttributesNames = function () {
  25782. return this._attributesNames;
  25783. };
  25784. Effect.prototype.getAttributeLocation = function (index) {
  25785. return this._attributes[index];
  25786. };
  25787. Effect.prototype.getAttributeLocationByName = function (name) {
  25788. var index = this._attributesNames.indexOf(name);
  25789. return this._attributes[index];
  25790. };
  25791. Effect.prototype.getAttributesCount = function () {
  25792. return this._attributes.length;
  25793. };
  25794. Effect.prototype.getUniformIndex = function (uniformName) {
  25795. return this._uniformsNames.indexOf(uniformName);
  25796. };
  25797. Effect.prototype.getUniform = function (uniformName) {
  25798. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25799. };
  25800. Effect.prototype.getSamplers = function () {
  25801. return this._samplers;
  25802. };
  25803. Effect.prototype.getCompilationError = function () {
  25804. return this._compilationError;
  25805. };
  25806. // Methods
  25807. Effect.prototype.executeWhenCompiled = function (func) {
  25808. if (this.isReady()) {
  25809. func(this);
  25810. return;
  25811. }
  25812. this.onCompileObservable.add(function (effect) {
  25813. func(effect);
  25814. });
  25815. };
  25816. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25817. if (BABYLON.Tools.IsWindowObjectExist()) {
  25818. // DOM element ?
  25819. if (vertex instanceof HTMLElement) {
  25820. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25821. callback(vertexCode);
  25822. return;
  25823. }
  25824. }
  25825. // Base64 encoded ?
  25826. if (vertex.substr(0, 7) === "base64:") {
  25827. var vertexBinary = window.atob(vertex.substr(7));
  25828. callback(vertexBinary);
  25829. return;
  25830. }
  25831. // Is in local store ?
  25832. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25833. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25834. return;
  25835. }
  25836. var vertexShaderUrl;
  25837. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25838. vertexShaderUrl = vertex;
  25839. }
  25840. else {
  25841. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25842. }
  25843. // Vertex shader
  25844. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25845. };
  25846. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25847. if (BABYLON.Tools.IsWindowObjectExist()) {
  25848. // DOM element ?
  25849. if (fragment instanceof HTMLElement) {
  25850. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25851. callback(fragmentCode);
  25852. return;
  25853. }
  25854. }
  25855. // Base64 encoded ?
  25856. if (fragment.substr(0, 7) === "base64:") {
  25857. var fragmentBinary = window.atob(fragment.substr(7));
  25858. callback(fragmentBinary);
  25859. return;
  25860. }
  25861. // Is in local store ?
  25862. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25863. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25864. return;
  25865. }
  25866. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25867. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25868. return;
  25869. }
  25870. var fragmentShaderUrl;
  25871. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25872. fragmentShaderUrl = fragment;
  25873. }
  25874. else {
  25875. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25876. }
  25877. // Fragment shader
  25878. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25879. };
  25880. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  25881. // Rebuild shaders source code
  25882. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  25883. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  25884. vertexCode = prefix + vertexCode;
  25885. fragmentCode = prefix + fragmentCode;
  25886. // Number lines of shaders source code
  25887. var i = 2;
  25888. var regex = /\n/gm;
  25889. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25890. i = 2;
  25891. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25892. // Dump shaders name and formatted source code
  25893. if (this.name.vertexElement) {
  25894. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  25895. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  25896. }
  25897. else if (this.name.vertex) {
  25898. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  25899. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  25900. }
  25901. else {
  25902. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  25903. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  25904. }
  25905. };
  25906. ;
  25907. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25908. var preparedSourceCode = this._processPrecision(sourceCode);
  25909. if (this._engine.webGLVersion == 1) {
  25910. callback(preparedSourceCode);
  25911. return;
  25912. }
  25913. // Already converted
  25914. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25915. callback(preparedSourceCode.replace("#version 300 es", ""));
  25916. return;
  25917. }
  25918. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  25919. // Remove extensions
  25920. // #extension GL_OES_standard_derivatives : enable
  25921. // #extension GL_EXT_shader_texture_lod : enable
  25922. // #extension GL_EXT_frag_depth : enable
  25923. // #extension GL_EXT_draw_buffers : require
  25924. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  25925. var result = preparedSourceCode.replace(regex, "");
  25926. // Migrate to GLSL v300
  25927. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  25928. result = result.replace(/attribute[ \t]/g, "in ");
  25929. result = result.replace(/[ \t]attribute/g, " in");
  25930. if (isFragment) {
  25931. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  25932. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  25933. result = result.replace(/texture2D\s*\(/g, "texture(");
  25934. result = result.replace(/textureCube\s*\(/g, "texture(");
  25935. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25936. result = result.replace(/gl_FragColor/g, "glFragColor");
  25937. result = result.replace(/gl_FragData/g, "glFragData");
  25938. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  25939. }
  25940. callback(result);
  25941. };
  25942. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25943. var _this = this;
  25944. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25945. var match = regex.exec(sourceCode);
  25946. var returnValue = new String(sourceCode);
  25947. while (match != null) {
  25948. var includeFile = match[1];
  25949. // Uniform declaration
  25950. if (includeFile.indexOf("__decl__") !== -1) {
  25951. includeFile = includeFile.replace(/__decl__/, "");
  25952. if (this._engine.supportsUniformBuffers) {
  25953. includeFile = includeFile.replace(/Vertex/, "Ubo");
  25954. includeFile = includeFile.replace(/Fragment/, "Ubo");
  25955. }
  25956. includeFile = includeFile + "Declaration";
  25957. }
  25958. if (Effect.IncludesShadersStore[includeFile]) {
  25959. // Substitution
  25960. var includeContent = Effect.IncludesShadersStore[includeFile];
  25961. if (match[2]) {
  25962. var splits = match[3].split(",");
  25963. for (var index = 0; index < splits.length; index += 2) {
  25964. var source = new RegExp(splits[index], "g");
  25965. var dest = splits[index + 1];
  25966. includeContent = includeContent.replace(source, dest);
  25967. }
  25968. }
  25969. if (match[4]) {
  25970. var indexString = match[5];
  25971. if (indexString.indexOf("..") !== -1) {
  25972. var indexSplits = indexString.split("..");
  25973. var minIndex = parseInt(indexSplits[0]);
  25974. var maxIndex = parseInt(indexSplits[1]);
  25975. var sourceIncludeContent = includeContent.slice(0);
  25976. includeContent = "";
  25977. if (isNaN(maxIndex)) {
  25978. maxIndex = this._indexParameters[indexSplits[1]];
  25979. }
  25980. for (var i = minIndex; i < maxIndex; i++) {
  25981. if (!this._engine.supportsUniformBuffers) {
  25982. // Ubo replacement
  25983. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25984. return p1 + "{X}";
  25985. });
  25986. }
  25987. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  25988. }
  25989. }
  25990. else {
  25991. if (!this._engine.supportsUniformBuffers) {
  25992. // Ubo replacement
  25993. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25994. return p1 + "{X}";
  25995. });
  25996. }
  25997. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25998. }
  25999. }
  26000. // Replace
  26001. returnValue = returnValue.replace(match[0], includeContent);
  26002. }
  26003. else {
  26004. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26005. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26006. Effect.IncludesShadersStore[includeFile] = fileContent;
  26007. _this._processIncludes(returnValue, callback);
  26008. });
  26009. return;
  26010. }
  26011. match = regex.exec(sourceCode);
  26012. }
  26013. callback(returnValue);
  26014. };
  26015. Effect.prototype._processPrecision = function (source) {
  26016. if (source.indexOf("precision highp float") === -1) {
  26017. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26018. source = "precision mediump float;\n" + source;
  26019. }
  26020. else {
  26021. source = "precision highp float;\n" + source;
  26022. }
  26023. }
  26024. else {
  26025. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26026. source = source.replace("precision highp float", "precision mediump float");
  26027. }
  26028. }
  26029. return source;
  26030. };
  26031. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26032. var _this = this;
  26033. this._isReady = false;
  26034. this._vertexSourceCodeOverride = vertexSourceCode;
  26035. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26036. this.onError = function (effect, error) {
  26037. if (onError) {
  26038. onError(error);
  26039. }
  26040. };
  26041. this.onCompiled = function () {
  26042. var scenes = _this.getEngine().scenes;
  26043. for (var i = 0; i < scenes.length; i++) {
  26044. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26045. }
  26046. if (onCompiled) {
  26047. onCompiled(_this._program);
  26048. }
  26049. };
  26050. this._fallbacks = null;
  26051. this._prepareEffect();
  26052. };
  26053. Effect.prototype._prepareEffect = function () {
  26054. var attributesNames = this._attributesNames;
  26055. var defines = this.defines;
  26056. var fallbacks = this._fallbacks;
  26057. this._valueCache = {};
  26058. var previousProgram = this._program;
  26059. try {
  26060. var engine = this._engine;
  26061. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26062. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26063. }
  26064. else {
  26065. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26066. }
  26067. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26068. if (engine.webGLVersion > 1) {
  26069. for (var name in this._uniformBuffersNames) {
  26070. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26071. }
  26072. }
  26073. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26074. this._attributes = engine.getAttributes(this._program, attributesNames);
  26075. var index;
  26076. for (index = 0; index < this._samplers.length; index++) {
  26077. var sampler = this.getUniform(this._samplers[index]);
  26078. if (sampler == null) {
  26079. this._samplers.splice(index, 1);
  26080. index--;
  26081. }
  26082. }
  26083. engine.bindSamplers(this);
  26084. this._compilationError = "";
  26085. this._isReady = true;
  26086. if (this.onCompiled) {
  26087. this.onCompiled(this);
  26088. }
  26089. this.onCompileObservable.notifyObservers(this);
  26090. this.onCompileObservable.clear();
  26091. // Unbind mesh reference in fallbacks
  26092. if (this._fallbacks) {
  26093. this._fallbacks.unBindMesh();
  26094. }
  26095. if (previousProgram) {
  26096. this.getEngine()._deleteProgram(previousProgram);
  26097. }
  26098. }
  26099. catch (e) {
  26100. this._compilationError = e.message;
  26101. // Let's go through fallbacks then
  26102. BABYLON.Tools.Error("Unable to compile effect:");
  26103. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26104. return " " + uniform;
  26105. }));
  26106. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26107. return " " + attribute;
  26108. }));
  26109. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26110. BABYLON.Tools.Error("Error: " + this._compilationError);
  26111. if (previousProgram) {
  26112. this._program = previousProgram;
  26113. this._isReady = true;
  26114. if (this.onError) {
  26115. this.onError(this, this._compilationError);
  26116. }
  26117. this.onErrorObservable.notifyObservers(this);
  26118. }
  26119. if (fallbacks && fallbacks.isMoreFallbacks) {
  26120. BABYLON.Tools.Error("Trying next fallback.");
  26121. this.defines = fallbacks.reduce(this.defines);
  26122. this._prepareEffect();
  26123. }
  26124. else {
  26125. if (this.onError) {
  26126. this.onError(this, this._compilationError);
  26127. }
  26128. this.onErrorObservable.notifyObservers(this);
  26129. this.onErrorObservable.clear();
  26130. // Unbind mesh reference in fallbacks
  26131. if (this._fallbacks) {
  26132. this._fallbacks.unBindMesh();
  26133. }
  26134. }
  26135. }
  26136. };
  26137. Object.defineProperty(Effect.prototype, "isSupported", {
  26138. get: function () {
  26139. return this._compilationError === "";
  26140. },
  26141. enumerable: true,
  26142. configurable: true
  26143. });
  26144. Effect.prototype._bindTexture = function (channel, texture) {
  26145. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26146. };
  26147. Effect.prototype.setTexture = function (channel, texture) {
  26148. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26149. };
  26150. Effect.prototype.setTextureArray = function (channel, textures) {
  26151. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26152. var initialPos = this._samplers.indexOf(channel);
  26153. for (var index = 1; index < textures.length; index++) {
  26154. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26155. }
  26156. }
  26157. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26158. };
  26159. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26160. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26161. };
  26162. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26163. var cache = this._valueCache[uniformName];
  26164. var flag = matrix.updateFlag;
  26165. if (cache !== undefined && cache === flag) {
  26166. return false;
  26167. }
  26168. this._valueCache[uniformName] = flag;
  26169. return true;
  26170. };
  26171. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26172. var cache = this._valueCache[uniformName];
  26173. if (!cache) {
  26174. cache = [x, y];
  26175. this._valueCache[uniformName] = cache;
  26176. return true;
  26177. }
  26178. var changed = false;
  26179. if (cache[0] !== x) {
  26180. cache[0] = x;
  26181. changed = true;
  26182. }
  26183. if (cache[1] !== y) {
  26184. cache[1] = y;
  26185. changed = true;
  26186. }
  26187. return changed;
  26188. };
  26189. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26190. var cache = this._valueCache[uniformName];
  26191. if (!cache) {
  26192. cache = [x, y, z];
  26193. this._valueCache[uniformName] = cache;
  26194. return true;
  26195. }
  26196. var changed = false;
  26197. if (cache[0] !== x) {
  26198. cache[0] = x;
  26199. changed = true;
  26200. }
  26201. if (cache[1] !== y) {
  26202. cache[1] = y;
  26203. changed = true;
  26204. }
  26205. if (cache[2] !== z) {
  26206. cache[2] = z;
  26207. changed = true;
  26208. }
  26209. return changed;
  26210. };
  26211. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26212. var cache = this._valueCache[uniformName];
  26213. if (!cache) {
  26214. cache = [x, y, z, w];
  26215. this._valueCache[uniformName] = cache;
  26216. return true;
  26217. }
  26218. var changed = false;
  26219. if (cache[0] !== x) {
  26220. cache[0] = x;
  26221. changed = true;
  26222. }
  26223. if (cache[1] !== y) {
  26224. cache[1] = y;
  26225. changed = true;
  26226. }
  26227. if (cache[2] !== z) {
  26228. cache[2] = z;
  26229. changed = true;
  26230. }
  26231. if (cache[3] !== w) {
  26232. cache[3] = w;
  26233. changed = true;
  26234. }
  26235. return changed;
  26236. };
  26237. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26238. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  26239. return;
  26240. }
  26241. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  26242. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  26243. };
  26244. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26245. this._engine.bindUniformBlock(this._program, blockName, index);
  26246. };
  26247. Effect.prototype.setIntArray = function (uniformName, array) {
  26248. this._valueCache[uniformName] = null;
  26249. this._engine.setIntArray(this.getUniform(uniformName), array);
  26250. return this;
  26251. };
  26252. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26253. this._valueCache[uniformName] = null;
  26254. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26255. return this;
  26256. };
  26257. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26258. this._valueCache[uniformName] = null;
  26259. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26260. return this;
  26261. };
  26262. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26263. this._valueCache[uniformName] = null;
  26264. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26265. return this;
  26266. };
  26267. Effect.prototype.setFloatArray = function (uniformName, array) {
  26268. this._valueCache[uniformName] = null;
  26269. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26270. return this;
  26271. };
  26272. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26273. this._valueCache[uniformName] = null;
  26274. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26275. return this;
  26276. };
  26277. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26278. this._valueCache[uniformName] = null;
  26279. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26280. return this;
  26281. };
  26282. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26283. this._valueCache[uniformName] = null;
  26284. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26285. return this;
  26286. };
  26287. Effect.prototype.setArray = function (uniformName, array) {
  26288. this._valueCache[uniformName] = null;
  26289. this._engine.setArray(this.getUniform(uniformName), array);
  26290. return this;
  26291. };
  26292. Effect.prototype.setArray2 = function (uniformName, array) {
  26293. this._valueCache[uniformName] = null;
  26294. this._engine.setArray2(this.getUniform(uniformName), array);
  26295. return this;
  26296. };
  26297. Effect.prototype.setArray3 = function (uniformName, array) {
  26298. this._valueCache[uniformName] = null;
  26299. this._engine.setArray3(this.getUniform(uniformName), array);
  26300. return this;
  26301. };
  26302. Effect.prototype.setArray4 = function (uniformName, array) {
  26303. this._valueCache[uniformName] = null;
  26304. this._engine.setArray4(this.getUniform(uniformName), array);
  26305. return this;
  26306. };
  26307. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26308. if (!matrices) {
  26309. return this;
  26310. }
  26311. this._valueCache[uniformName] = null;
  26312. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26313. return this;
  26314. };
  26315. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26316. if (this._cacheMatrix(uniformName, matrix)) {
  26317. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26318. }
  26319. return this;
  26320. };
  26321. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26322. this._valueCache[uniformName] = null;
  26323. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26324. return this;
  26325. };
  26326. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26327. this._valueCache[uniformName] = null;
  26328. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26329. return this;
  26330. };
  26331. Effect.prototype.setFloat = function (uniformName, value) {
  26332. var cache = this._valueCache[uniformName];
  26333. if (cache !== undefined && cache === value)
  26334. return this;
  26335. this._valueCache[uniformName] = value;
  26336. this._engine.setFloat(this.getUniform(uniformName), value);
  26337. return this;
  26338. };
  26339. Effect.prototype.setBool = function (uniformName, bool) {
  26340. var cache = this._valueCache[uniformName];
  26341. if (cache !== undefined && cache === bool)
  26342. return this;
  26343. this._valueCache[uniformName] = bool;
  26344. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26345. return this;
  26346. };
  26347. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26348. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26349. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26350. }
  26351. return this;
  26352. };
  26353. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26354. if (this._cacheFloat2(uniformName, x, y)) {
  26355. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26356. }
  26357. return this;
  26358. };
  26359. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26360. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26361. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26362. }
  26363. return this;
  26364. };
  26365. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26366. if (this._cacheFloat3(uniformName, x, y, z)) {
  26367. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26368. }
  26369. return this;
  26370. };
  26371. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26372. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26373. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26374. }
  26375. return this;
  26376. };
  26377. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26378. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26379. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26380. }
  26381. return this;
  26382. };
  26383. Effect.prototype.setColor3 = function (uniformName, color3) {
  26384. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26385. this._engine.setColor3(this.getUniform(uniformName), color3);
  26386. }
  26387. return this;
  26388. };
  26389. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26390. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26391. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26392. }
  26393. return this;
  26394. };
  26395. Effect.ResetCache = function () {
  26396. Effect._baseCache = {};
  26397. };
  26398. Effect._uniqueIdSeed = 0;
  26399. Effect._baseCache = {};
  26400. // Statics
  26401. Effect.ShadersStore = {};
  26402. Effect.IncludesShadersStore = {};
  26403. return Effect;
  26404. }());
  26405. BABYLON.Effect = Effect;
  26406. })(BABYLON || (BABYLON = {}));
  26407. //# sourceMappingURL=babylon.effect.js.map
  26408. var BABYLON;
  26409. (function (BABYLON) {
  26410. var MaterialHelper = /** @class */ (function () {
  26411. function MaterialHelper() {
  26412. }
  26413. MaterialHelper.BindEyePosition = function (effect, scene) {
  26414. if (scene._forcedViewPosition) {
  26415. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  26416. return;
  26417. }
  26418. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  26419. };
  26420. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26421. defines._needUVs = true;
  26422. defines[key] = true;
  26423. if (texture.getTextureMatrix().isIdentity(true)) {
  26424. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26425. if (texture.coordinatesIndex === 0) {
  26426. defines["MAINUV1"] = true;
  26427. }
  26428. else {
  26429. defines["MAINUV2"] = true;
  26430. }
  26431. }
  26432. else {
  26433. defines[key + "DIRECTUV"] = 0;
  26434. }
  26435. };
  26436. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26437. var matrix = texture.getTextureMatrix();
  26438. if (!matrix.isIdentity(true)) {
  26439. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26440. }
  26441. };
  26442. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26443. if (defines._areMiscDirty) {
  26444. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26445. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26446. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26447. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26448. }
  26449. };
  26450. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26451. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26452. var changed = false;
  26453. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26454. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26455. changed = true;
  26456. }
  26457. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26458. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26459. changed = true;
  26460. }
  26461. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26462. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26463. changed = true;
  26464. }
  26465. if (defines["INSTANCES"] !== useInstances) {
  26466. defines["INSTANCES"] = useInstances;
  26467. changed = true;
  26468. }
  26469. if (changed) {
  26470. defines.markAsUnprocessed();
  26471. }
  26472. };
  26473. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  26474. if (useMorphTargets === void 0) { useMorphTargets = false; }
  26475. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  26476. return false;
  26477. }
  26478. defines._normals = defines._needNormals;
  26479. defines._uvs = defines._needUVs;
  26480. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  26481. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26482. defines["TANGENT"] = true;
  26483. }
  26484. if (defines._needUVs) {
  26485. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  26486. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  26487. }
  26488. else {
  26489. defines["UV1"] = false;
  26490. defines["UV2"] = false;
  26491. }
  26492. if (useVertexColor) {
  26493. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  26494. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  26495. }
  26496. if (useBones) {
  26497. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26498. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  26499. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  26500. }
  26501. else {
  26502. defines["NUM_BONE_INFLUENCERS"] = 0;
  26503. defines["BonesPerMesh"] = 0;
  26504. }
  26505. }
  26506. if (useMorphTargets) {
  26507. var manager = mesh.morphTargetManager;
  26508. if (manager) {
  26509. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  26510. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  26511. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  26512. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  26513. }
  26514. else {
  26515. defines["MORPHTARGETS_TANGENT"] = false;
  26516. defines["MORPHTARGETS_NORMAL"] = false;
  26517. defines["MORPHTARGETS"] = false;
  26518. defines["NUM_MORPH_INFLUENCERS"] = 0;
  26519. }
  26520. }
  26521. return true;
  26522. };
  26523. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  26524. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26525. if (disableLighting === void 0) { disableLighting = false; }
  26526. if (!defines._areLightsDirty) {
  26527. return defines._needNormals;
  26528. }
  26529. var lightIndex = 0;
  26530. var needNormals = false;
  26531. var needRebuild = false;
  26532. var lightmapMode = false;
  26533. var shadowEnabled = false;
  26534. var specularEnabled = false;
  26535. if (scene.lightsEnabled && !disableLighting) {
  26536. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26537. var light = _a[_i];
  26538. needNormals = true;
  26539. if (defines["LIGHT" + lightIndex] === undefined) {
  26540. needRebuild = true;
  26541. }
  26542. defines["LIGHT" + lightIndex] = true;
  26543. defines["SPOTLIGHT" + lightIndex] = false;
  26544. defines["HEMILIGHT" + lightIndex] = false;
  26545. defines["POINTLIGHT" + lightIndex] = false;
  26546. defines["DIRLIGHT" + lightIndex] = false;
  26547. var type;
  26548. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  26549. type = "SPOTLIGHT" + lightIndex;
  26550. }
  26551. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  26552. type = "HEMILIGHT" + lightIndex;
  26553. }
  26554. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  26555. type = "POINTLIGHT" + lightIndex;
  26556. }
  26557. else {
  26558. type = "DIRLIGHT" + lightIndex;
  26559. }
  26560. defines[type] = true;
  26561. // Specular
  26562. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  26563. specularEnabled = true;
  26564. }
  26565. // Shadows
  26566. defines["SHADOW" + lightIndex] = false;
  26567. defines["SHADOWPCF" + lightIndex] = false;
  26568. defines["SHADOWESM" + lightIndex] = false;
  26569. defines["SHADOWCUBE" + lightIndex] = false;
  26570. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  26571. var shadowGenerator = light.getShadowGenerator();
  26572. if (shadowGenerator) {
  26573. shadowEnabled = true;
  26574. shadowGenerator.prepareDefines(defines, lightIndex);
  26575. }
  26576. }
  26577. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26578. lightmapMode = true;
  26579. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26580. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  26581. }
  26582. else {
  26583. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  26584. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  26585. }
  26586. lightIndex++;
  26587. if (lightIndex === maxSimultaneousLights)
  26588. break;
  26589. }
  26590. }
  26591. defines["SPECULARTERM"] = specularEnabled;
  26592. defines["SHADOWS"] = shadowEnabled;
  26593. // Resetting all other lights if any
  26594. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  26595. if (defines["LIGHT" + index] !== undefined) {
  26596. defines["LIGHT" + index] = false;
  26597. defines["HEMILIGHT" + lightIndex] = false;
  26598. defines["POINTLIGHT" + lightIndex] = false;
  26599. defines["DIRLIGHT" + lightIndex] = false;
  26600. defines["SPOTLIGHT" + lightIndex] = false;
  26601. defines["SHADOW" + lightIndex] = false;
  26602. }
  26603. }
  26604. var caps = scene.getEngine().getCaps();
  26605. if (defines["SHADOWFLOAT"] === undefined) {
  26606. needRebuild = true;
  26607. }
  26608. defines["SHADOWFLOAT"] = shadowEnabled &&
  26609. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  26610. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  26611. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  26612. if (needRebuild) {
  26613. defines.rebuild();
  26614. }
  26615. return needNormals;
  26616. };
  26617. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  26618. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26619. var uniformsList;
  26620. var uniformBuffersList = null;
  26621. if (uniformsListOrOptions.uniformsNames) {
  26622. var options = uniformsListOrOptions;
  26623. uniformsList = options.uniformsNames;
  26624. uniformBuffersList = options.uniformBuffersNames;
  26625. samplersList = options.samplers;
  26626. defines = options.defines;
  26627. maxSimultaneousLights = options.maxSimultaneousLights;
  26628. }
  26629. else {
  26630. uniformsList = uniformsListOrOptions;
  26631. if (!samplersList) {
  26632. samplersList = [];
  26633. }
  26634. }
  26635. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26636. if (!defines["LIGHT" + lightIndex]) {
  26637. break;
  26638. }
  26639. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  26640. if (uniformBuffersList) {
  26641. uniformBuffersList.push("Light" + lightIndex);
  26642. }
  26643. samplersList.push("shadowSampler" + lightIndex);
  26644. }
  26645. if (defines["NUM_MORPH_INFLUENCERS"]) {
  26646. uniformsList.push("morphTargetInfluences");
  26647. }
  26648. };
  26649. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  26650. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26651. if (rank === void 0) { rank = 0; }
  26652. var lightFallbackRank = 0;
  26653. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26654. if (!defines["LIGHT" + lightIndex]) {
  26655. break;
  26656. }
  26657. if (lightIndex > 0) {
  26658. lightFallbackRank = rank + lightIndex;
  26659. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  26660. }
  26661. if (!defines["SHADOWS"]) {
  26662. if (defines["SHADOW" + lightIndex]) {
  26663. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  26664. }
  26665. if (defines["SHADOWPCF" + lightIndex]) {
  26666. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  26667. }
  26668. if (defines["SHADOWESM" + lightIndex]) {
  26669. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  26670. }
  26671. }
  26672. }
  26673. return lightFallbackRank++;
  26674. };
  26675. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  26676. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  26677. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  26678. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  26679. var manager = mesh.morphTargetManager;
  26680. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  26681. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  26682. for (var index = 0; index < influencers; index++) {
  26683. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  26684. if (normal) {
  26685. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  26686. }
  26687. if (tangent) {
  26688. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  26689. }
  26690. if (attribs.length > maxAttributesCount) {
  26691. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  26692. }
  26693. }
  26694. }
  26695. };
  26696. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26697. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26698. fallbacks.addCPUSkinningFallback(0, mesh);
  26699. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26700. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26701. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26702. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26703. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26704. }
  26705. }
  26706. };
  26707. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26708. if (defines["INSTANCES"]) {
  26709. attribs.push("world0");
  26710. attribs.push("world1");
  26711. attribs.push("world2");
  26712. attribs.push("world3");
  26713. }
  26714. };
  26715. // Bindings
  26716. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  26717. if (light.shadowEnabled && mesh.receiveShadows) {
  26718. var shadowGenerator = light.getShadowGenerator();
  26719. if (shadowGenerator) {
  26720. shadowGenerator.bindShadowLight(lightIndex, effect);
  26721. }
  26722. }
  26723. };
  26724. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26725. light.transferToEffect(effect, lightIndex + "");
  26726. };
  26727. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  26728. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26729. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  26730. var lightIndex = 0;
  26731. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26732. var light = _a[_i];
  26733. var scaledIntensity = light.getScaledIntensity();
  26734. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  26735. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26736. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  26737. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  26738. if (defines["SPECULARTERM"]) {
  26739. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  26740. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  26741. }
  26742. // Shadows
  26743. if (scene.shadowsEnabled) {
  26744. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  26745. }
  26746. light._uniformBuffer.update();
  26747. lightIndex++;
  26748. if (lightIndex === maxSimultaneousLights)
  26749. break;
  26750. }
  26751. };
  26752. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26753. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26754. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26755. effect.setColor3("vFogColor", scene.fogColor);
  26756. }
  26757. };
  26758. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26759. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26760. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26761. if (matrices && effect) {
  26762. effect.setMatrices("mBones", matrices);
  26763. }
  26764. }
  26765. };
  26766. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  26767. var manager = abstractMesh.morphTargetManager;
  26768. if (!abstractMesh || !manager) {
  26769. return;
  26770. }
  26771. effect.setFloatArray("morphTargetInfluences", manager.influences);
  26772. };
  26773. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26774. if (defines["LOGARITHMICDEPTH"]) {
  26775. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26776. }
  26777. };
  26778. MaterialHelper.BindClipPlane = function (effect, scene) {
  26779. if (scene.clipPlane) {
  26780. var clipPlane = scene.clipPlane;
  26781. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26782. }
  26783. };
  26784. return MaterialHelper;
  26785. }());
  26786. BABYLON.MaterialHelper = MaterialHelper;
  26787. })(BABYLON || (BABYLON = {}));
  26788. //# sourceMappingURL=babylon.materialHelper.js.map
  26789. var BABYLON;
  26790. (function (BABYLON) {
  26791. var MaterialDefines = /** @class */ (function () {
  26792. function MaterialDefines() {
  26793. this._isDirty = true;
  26794. this._areLightsDirty = true;
  26795. this._areAttributesDirty = true;
  26796. this._areTexturesDirty = true;
  26797. this._areFresnelDirty = true;
  26798. this._areMiscDirty = true;
  26799. this._areImageProcessingDirty = true;
  26800. this._normals = false;
  26801. this._uvs = false;
  26802. this._needNormals = false;
  26803. this._needUVs = false;
  26804. }
  26805. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  26806. get: function () {
  26807. return this._isDirty;
  26808. },
  26809. enumerable: true,
  26810. configurable: true
  26811. });
  26812. MaterialDefines.prototype.markAsProcessed = function () {
  26813. this._isDirty = false;
  26814. this._areAttributesDirty = false;
  26815. this._areTexturesDirty = false;
  26816. this._areFresnelDirty = false;
  26817. this._areLightsDirty = false;
  26818. this._areMiscDirty = false;
  26819. this._areImageProcessingDirty = false;
  26820. };
  26821. MaterialDefines.prototype.markAsUnprocessed = function () {
  26822. this._isDirty = true;
  26823. };
  26824. MaterialDefines.prototype.markAllAsDirty = function () {
  26825. this._areTexturesDirty = true;
  26826. this._areAttributesDirty = true;
  26827. this._areLightsDirty = true;
  26828. this._areFresnelDirty = true;
  26829. this._areMiscDirty = true;
  26830. this._areImageProcessingDirty = true;
  26831. this._isDirty = true;
  26832. };
  26833. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  26834. this._areImageProcessingDirty = true;
  26835. this._isDirty = true;
  26836. };
  26837. MaterialDefines.prototype.markAsLightDirty = function () {
  26838. this._areLightsDirty = true;
  26839. this._isDirty = true;
  26840. };
  26841. MaterialDefines.prototype.markAsAttributesDirty = function () {
  26842. this._areAttributesDirty = true;
  26843. this._isDirty = true;
  26844. };
  26845. MaterialDefines.prototype.markAsTexturesDirty = function () {
  26846. this._areTexturesDirty = true;
  26847. this._isDirty = true;
  26848. };
  26849. MaterialDefines.prototype.markAsFresnelDirty = function () {
  26850. this._areFresnelDirty = true;
  26851. this._isDirty = true;
  26852. };
  26853. MaterialDefines.prototype.markAsMiscDirty = function () {
  26854. this._areMiscDirty = true;
  26855. this._isDirty = true;
  26856. };
  26857. MaterialDefines.prototype.rebuild = function () {
  26858. if (this._keys) {
  26859. delete this._keys;
  26860. }
  26861. this._keys = [];
  26862. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  26863. var key = _a[_i];
  26864. if (key[0] === "_") {
  26865. continue;
  26866. }
  26867. this._keys.push(key);
  26868. }
  26869. };
  26870. MaterialDefines.prototype.isEqual = function (other) {
  26871. if (this._keys.length !== other._keys.length) {
  26872. return false;
  26873. }
  26874. for (var index = 0; index < this._keys.length; index++) {
  26875. var prop = this._keys[index];
  26876. if (this[prop] !== other[prop]) {
  26877. return false;
  26878. }
  26879. }
  26880. return true;
  26881. };
  26882. MaterialDefines.prototype.cloneTo = function (other) {
  26883. if (this._keys.length !== other._keys.length) {
  26884. other._keys = this._keys.slice(0);
  26885. }
  26886. for (var index = 0; index < this._keys.length; index++) {
  26887. var prop = this._keys[index];
  26888. other[prop] = this[prop];
  26889. }
  26890. };
  26891. MaterialDefines.prototype.reset = function () {
  26892. for (var index = 0; index < this._keys.length; index++) {
  26893. var prop = this._keys[index];
  26894. if (typeof (this[prop]) === "number") {
  26895. this[prop] = 0;
  26896. }
  26897. else {
  26898. this[prop] = false;
  26899. }
  26900. }
  26901. };
  26902. MaterialDefines.prototype.toString = function () {
  26903. var result = "";
  26904. for (var index = 0; index < this._keys.length; index++) {
  26905. var prop = this._keys[index];
  26906. var value = this[prop];
  26907. if (typeof (value) === "number") {
  26908. result += "#define " + prop + " " + this[prop] + "\n";
  26909. }
  26910. else if (value) {
  26911. result += "#define " + prop + "\n";
  26912. }
  26913. }
  26914. return result;
  26915. };
  26916. return MaterialDefines;
  26917. }());
  26918. BABYLON.MaterialDefines = MaterialDefines;
  26919. var Material = /** @class */ (function () {
  26920. function Material(name, scene, doNotAdd) {
  26921. this.checkReadyOnEveryCall = false;
  26922. this.checkReadyOnlyOnce = false;
  26923. this.state = "";
  26924. this.alpha = 1.0;
  26925. this._backFaceCulling = true;
  26926. this.doNotSerialize = false;
  26927. this.storeEffectOnSubMeshes = false;
  26928. /**
  26929. * An event triggered when the material is disposed.
  26930. * @type {BABYLON.Observable}
  26931. */
  26932. this.onDisposeObservable = new BABYLON.Observable();
  26933. /**
  26934. * An event triggered when the material is bound.
  26935. * @type {BABYLON.Observable}
  26936. */
  26937. this.onBindObservable = new BABYLON.Observable();
  26938. /**
  26939. * An event triggered when the material is unbound.
  26940. * @type {BABYLON.Observable}
  26941. */
  26942. this.onUnBindObservable = new BABYLON.Observable();
  26943. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26944. this._needDepthPrePass = false;
  26945. this.disableDepthWrite = false;
  26946. this.forceDepthWrite = false;
  26947. this.separateCullingPass = false;
  26948. this._fogEnabled = true;
  26949. this.pointSize = 1.0;
  26950. this.zOffset = 0;
  26951. this._wasPreviouslyReady = false;
  26952. this._fillMode = Material.TriangleFillMode;
  26953. this.name = name;
  26954. this.id = name || BABYLON.Tools.RandomId();
  26955. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26956. if (this._scene.useRightHandedSystem) {
  26957. this.sideOrientation = Material.ClockWiseSideOrientation;
  26958. }
  26959. else {
  26960. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26961. }
  26962. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  26963. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  26964. if (!doNotAdd) {
  26965. this._scene.materials.push(this);
  26966. }
  26967. }
  26968. Object.defineProperty(Material, "TriangleFillMode", {
  26969. get: function () {
  26970. return Material._TriangleFillMode;
  26971. },
  26972. enumerable: true,
  26973. configurable: true
  26974. });
  26975. Object.defineProperty(Material, "WireFrameFillMode", {
  26976. get: function () {
  26977. return Material._WireFrameFillMode;
  26978. },
  26979. enumerable: true,
  26980. configurable: true
  26981. });
  26982. Object.defineProperty(Material, "PointFillMode", {
  26983. get: function () {
  26984. return Material._PointFillMode;
  26985. },
  26986. enumerable: true,
  26987. configurable: true
  26988. });
  26989. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26990. get: function () {
  26991. return Material._ClockWiseSideOrientation;
  26992. },
  26993. enumerable: true,
  26994. configurable: true
  26995. });
  26996. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26997. get: function () {
  26998. return Material._CounterClockWiseSideOrientation;
  26999. },
  27000. enumerable: true,
  27001. configurable: true
  27002. });
  27003. Object.defineProperty(Material, "TextureDirtyFlag", {
  27004. get: function () {
  27005. return Material._TextureDirtyFlag;
  27006. },
  27007. enumerable: true,
  27008. configurable: true
  27009. });
  27010. Object.defineProperty(Material, "LightDirtyFlag", {
  27011. get: function () {
  27012. return Material._LightDirtyFlag;
  27013. },
  27014. enumerable: true,
  27015. configurable: true
  27016. });
  27017. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27018. get: function () {
  27019. return Material._FresnelDirtyFlag;
  27020. },
  27021. enumerable: true,
  27022. configurable: true
  27023. });
  27024. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27025. get: function () {
  27026. return Material._AttributesDirtyFlag;
  27027. },
  27028. enumerable: true,
  27029. configurable: true
  27030. });
  27031. Object.defineProperty(Material, "MiscDirtyFlag", {
  27032. get: function () {
  27033. return Material._MiscDirtyFlag;
  27034. },
  27035. enumerable: true,
  27036. configurable: true
  27037. });
  27038. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27039. get: function () {
  27040. return this._backFaceCulling;
  27041. },
  27042. set: function (value) {
  27043. if (this._backFaceCulling === value) {
  27044. return;
  27045. }
  27046. this._backFaceCulling = value;
  27047. this.markAsDirty(Material.TextureDirtyFlag);
  27048. },
  27049. enumerable: true,
  27050. configurable: true
  27051. });
  27052. Object.defineProperty(Material.prototype, "onDispose", {
  27053. set: function (callback) {
  27054. if (this._onDisposeObserver) {
  27055. this.onDisposeObservable.remove(this._onDisposeObserver);
  27056. }
  27057. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27058. },
  27059. enumerable: true,
  27060. configurable: true
  27061. });
  27062. Object.defineProperty(Material.prototype, "onBind", {
  27063. set: function (callback) {
  27064. if (this._onBindObserver) {
  27065. this.onBindObservable.remove(this._onBindObserver);
  27066. }
  27067. this._onBindObserver = this.onBindObservable.add(callback);
  27068. },
  27069. enumerable: true,
  27070. configurable: true
  27071. });
  27072. Object.defineProperty(Material.prototype, "alphaMode", {
  27073. get: function () {
  27074. return this._alphaMode;
  27075. },
  27076. set: function (value) {
  27077. if (this._alphaMode === value) {
  27078. return;
  27079. }
  27080. this._alphaMode = value;
  27081. this.markAsDirty(Material.TextureDirtyFlag);
  27082. },
  27083. enumerable: true,
  27084. configurable: true
  27085. });
  27086. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27087. get: function () {
  27088. return this._needDepthPrePass;
  27089. },
  27090. set: function (value) {
  27091. if (this._needDepthPrePass === value) {
  27092. return;
  27093. }
  27094. this._needDepthPrePass = value;
  27095. if (this._needDepthPrePass) {
  27096. this.checkReadyOnEveryCall = true;
  27097. }
  27098. },
  27099. enumerable: true,
  27100. configurable: true
  27101. });
  27102. Object.defineProperty(Material.prototype, "fogEnabled", {
  27103. get: function () {
  27104. return this._fogEnabled;
  27105. },
  27106. set: function (value) {
  27107. if (this._fogEnabled === value) {
  27108. return;
  27109. }
  27110. this._fogEnabled = value;
  27111. this.markAsDirty(Material.MiscDirtyFlag);
  27112. },
  27113. enumerable: true,
  27114. configurable: true
  27115. });
  27116. Object.defineProperty(Material.prototype, "wireframe", {
  27117. get: function () {
  27118. return this._fillMode === Material.WireFrameFillMode;
  27119. },
  27120. set: function (value) {
  27121. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27122. },
  27123. enumerable: true,
  27124. configurable: true
  27125. });
  27126. Object.defineProperty(Material.prototype, "pointsCloud", {
  27127. get: function () {
  27128. return this._fillMode === Material.PointFillMode;
  27129. },
  27130. set: function (value) {
  27131. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27132. },
  27133. enumerable: true,
  27134. configurable: true
  27135. });
  27136. Object.defineProperty(Material.prototype, "fillMode", {
  27137. get: function () {
  27138. return this._fillMode;
  27139. },
  27140. set: function (value) {
  27141. if (this._fillMode === value) {
  27142. return;
  27143. }
  27144. this._fillMode = value;
  27145. this.markAsDirty(Material.MiscDirtyFlag);
  27146. },
  27147. enumerable: true,
  27148. configurable: true
  27149. });
  27150. /**
  27151. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27152. * subclasses should override adding information pertainent to themselves
  27153. */
  27154. Material.prototype.toString = function (fullDetails) {
  27155. var ret = "Name: " + this.name;
  27156. if (fullDetails) {
  27157. }
  27158. return ret;
  27159. };
  27160. /**
  27161. * Child classes can use it to update shaders
  27162. */
  27163. Material.prototype.getClassName = function () {
  27164. return "Material";
  27165. };
  27166. Object.defineProperty(Material.prototype, "isFrozen", {
  27167. get: function () {
  27168. return this.checkReadyOnlyOnce;
  27169. },
  27170. enumerable: true,
  27171. configurable: true
  27172. });
  27173. Material.prototype.freeze = function () {
  27174. this.checkReadyOnlyOnce = true;
  27175. };
  27176. Material.prototype.unfreeze = function () {
  27177. this.checkReadyOnlyOnce = false;
  27178. };
  27179. Material.prototype.isReady = function (mesh, useInstances) {
  27180. return true;
  27181. };
  27182. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27183. return false;
  27184. };
  27185. Material.prototype.getEffect = function () {
  27186. return this._effect;
  27187. };
  27188. Material.prototype.getScene = function () {
  27189. return this._scene;
  27190. };
  27191. Material.prototype.needAlphaBlending = function () {
  27192. return (this.alpha < 1.0);
  27193. };
  27194. Material.prototype.needAlphaTesting = function () {
  27195. return false;
  27196. };
  27197. Material.prototype.getAlphaTestTexture = function () {
  27198. return null;
  27199. };
  27200. Material.prototype.markDirty = function () {
  27201. this._wasPreviouslyReady = false;
  27202. };
  27203. Material.prototype._preBind = function (effect, overrideOrientation) {
  27204. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27205. var engine = this._scene.getEngine();
  27206. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27207. var reverse = orientation === Material.ClockWiseSideOrientation;
  27208. engine.enableEffect(effect ? effect : this._effect);
  27209. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27210. return reverse;
  27211. };
  27212. Material.prototype.bind = function (world, mesh) {
  27213. };
  27214. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27215. };
  27216. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27217. };
  27218. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27219. sceneUbo.bindToEffect(effect, "Scene");
  27220. };
  27221. Material.prototype.bindView = function (effect) {
  27222. if (!this._useUBO) {
  27223. effect.setMatrix("view", this.getScene().getViewMatrix());
  27224. }
  27225. else {
  27226. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27227. }
  27228. };
  27229. Material.prototype.bindViewProjection = function (effect) {
  27230. if (!this._useUBO) {
  27231. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27232. }
  27233. else {
  27234. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27235. }
  27236. };
  27237. Material.prototype._afterBind = function (mesh) {
  27238. this._scene._cachedMaterial = this;
  27239. if (mesh) {
  27240. this._scene._cachedVisibility = mesh.visibility;
  27241. }
  27242. else {
  27243. this._scene._cachedVisibility = 1;
  27244. }
  27245. if (mesh) {
  27246. this.onBindObservable.notifyObservers(mesh);
  27247. }
  27248. if (this.disableDepthWrite) {
  27249. var engine = this._scene.getEngine();
  27250. this._cachedDepthWriteState = engine.getDepthWrite();
  27251. engine.setDepthWrite(false);
  27252. }
  27253. };
  27254. Material.prototype.unbind = function () {
  27255. this.onUnBindObservable.notifyObservers(this);
  27256. if (this.disableDepthWrite) {
  27257. var engine = this._scene.getEngine();
  27258. engine.setDepthWrite(this._cachedDepthWriteState);
  27259. }
  27260. };
  27261. Material.prototype.getActiveTextures = function () {
  27262. return [];
  27263. };
  27264. Material.prototype.hasTexture = function (texture) {
  27265. return false;
  27266. };
  27267. Material.prototype.clone = function (name) {
  27268. return null;
  27269. };
  27270. Material.prototype.getBindedMeshes = function () {
  27271. var result = new Array();
  27272. for (var index = 0; index < this._scene.meshes.length; index++) {
  27273. var mesh = this._scene.meshes[index];
  27274. if (mesh.material === this) {
  27275. result.push(mesh);
  27276. }
  27277. }
  27278. return result;
  27279. };
  27280. /**
  27281. * Force shader compilation including textures ready check
  27282. */
  27283. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27284. var _this = this;
  27285. var subMesh = new BABYLON.BaseSubMesh();
  27286. var scene = this.getScene();
  27287. var engine = scene.getEngine();
  27288. var checkReady = function () {
  27289. if (!_this._scene || !_this._scene.getEngine()) {
  27290. return;
  27291. }
  27292. if (subMesh._materialDefines) {
  27293. subMesh._materialDefines._renderId = -1;
  27294. }
  27295. var alphaTestState = engine.getAlphaTesting();
  27296. var clipPlaneState = scene.clipPlane;
  27297. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  27298. if (options && options.clipPlane) {
  27299. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27300. }
  27301. if (_this.storeEffectOnSubMeshes) {
  27302. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27303. if (onCompiled) {
  27304. onCompiled(_this);
  27305. }
  27306. }
  27307. else {
  27308. setTimeout(checkReady, 16);
  27309. }
  27310. }
  27311. else {
  27312. if (_this.isReady(mesh)) {
  27313. if (onCompiled) {
  27314. onCompiled(_this);
  27315. }
  27316. }
  27317. else {
  27318. setTimeout(checkReady, 16);
  27319. }
  27320. }
  27321. engine.setAlphaTesting(alphaTestState);
  27322. if (options && options.clipPlane) {
  27323. scene.clipPlane = clipPlaneState;
  27324. }
  27325. };
  27326. checkReady();
  27327. };
  27328. Material.prototype.markAsDirty = function (flag) {
  27329. if (flag & Material.TextureDirtyFlag) {
  27330. this._markAllSubMeshesAsTexturesDirty();
  27331. }
  27332. if (flag & Material.LightDirtyFlag) {
  27333. this._markAllSubMeshesAsLightsDirty();
  27334. }
  27335. if (flag & Material.FresnelDirtyFlag) {
  27336. this._markAllSubMeshesAsFresnelDirty();
  27337. }
  27338. if (flag & Material.AttributesDirtyFlag) {
  27339. this._markAllSubMeshesAsAttributesDirty();
  27340. }
  27341. if (flag & Material.MiscDirtyFlag) {
  27342. this._markAllSubMeshesAsMiscDirty();
  27343. }
  27344. this.getScene().resetCachedMaterial();
  27345. };
  27346. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27347. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27348. var mesh = _a[_i];
  27349. if (!mesh.subMeshes) {
  27350. continue;
  27351. }
  27352. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27353. var subMesh = _c[_b];
  27354. if (subMesh.getMaterial() !== this) {
  27355. continue;
  27356. }
  27357. if (!subMesh._materialDefines) {
  27358. continue;
  27359. }
  27360. func(subMesh._materialDefines);
  27361. }
  27362. }
  27363. };
  27364. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27365. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27366. };
  27367. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27368. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27369. };
  27370. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27371. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27372. };
  27373. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27374. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27375. };
  27376. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27377. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27378. };
  27379. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27380. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27381. };
  27382. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27383. // Animations
  27384. this.getScene().stopAnimation(this);
  27385. // Remove from scene
  27386. var index = this._scene.materials.indexOf(this);
  27387. if (index >= 0) {
  27388. this._scene.materials.splice(index, 1);
  27389. }
  27390. // Remove from meshes
  27391. for (index = 0; index < this._scene.meshes.length; index++) {
  27392. var mesh = this._scene.meshes[index];
  27393. if (mesh.material === this) {
  27394. mesh.material = null;
  27395. if (mesh.geometry) {
  27396. var geometry = (mesh.geometry);
  27397. if (this.storeEffectOnSubMeshes) {
  27398. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27399. var subMesh = _a[_i];
  27400. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27401. if (forceDisposeEffect && subMesh._materialEffect) {
  27402. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27403. }
  27404. }
  27405. }
  27406. else {
  27407. geometry._releaseVertexArrayObject(this._effect);
  27408. }
  27409. }
  27410. }
  27411. }
  27412. this._uniformBuffer.dispose();
  27413. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27414. if (forceDisposeEffect && this._effect) {
  27415. if (!this.storeEffectOnSubMeshes) {
  27416. this._scene.getEngine()._releaseEffect(this._effect);
  27417. }
  27418. this._effect = null;
  27419. }
  27420. // Callback
  27421. this.onDisposeObservable.notifyObservers(this);
  27422. this.onDisposeObservable.clear();
  27423. this.onBindObservable.clear();
  27424. this.onUnBindObservable.clear();
  27425. };
  27426. Material.prototype.serialize = function () {
  27427. return BABYLON.SerializationHelper.Serialize(this);
  27428. };
  27429. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27430. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27431. multiMaterial.id = parsedMultiMaterial.id;
  27432. if (BABYLON.Tags) {
  27433. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27434. }
  27435. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27436. var subMatId = parsedMultiMaterial.materials[matIndex];
  27437. if (subMatId) {
  27438. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27439. }
  27440. else {
  27441. multiMaterial.subMaterials.push(null);
  27442. }
  27443. }
  27444. return multiMaterial;
  27445. };
  27446. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27447. if (!parsedMaterial.customType) {
  27448. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27449. }
  27450. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27451. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27452. if (!BABYLON.LegacyPBRMaterial) {
  27453. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27454. return;
  27455. }
  27456. }
  27457. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27458. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27459. ;
  27460. };
  27461. Material._TriangleFillMode = 0;
  27462. Material._WireFrameFillMode = 1;
  27463. Material._PointFillMode = 2;
  27464. Material._ClockWiseSideOrientation = 0;
  27465. Material._CounterClockWiseSideOrientation = 1;
  27466. Material._TextureDirtyFlag = 1;
  27467. Material._LightDirtyFlag = 2;
  27468. Material._FresnelDirtyFlag = 4;
  27469. Material._AttributesDirtyFlag = 8;
  27470. Material._MiscDirtyFlag = 16;
  27471. __decorate([
  27472. BABYLON.serialize()
  27473. ], Material.prototype, "id", void 0);
  27474. __decorate([
  27475. BABYLON.serialize()
  27476. ], Material.prototype, "name", void 0);
  27477. __decorate([
  27478. BABYLON.serialize()
  27479. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27480. __decorate([
  27481. BABYLON.serialize()
  27482. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27483. __decorate([
  27484. BABYLON.serialize()
  27485. ], Material.prototype, "state", void 0);
  27486. __decorate([
  27487. BABYLON.serialize()
  27488. ], Material.prototype, "alpha", void 0);
  27489. __decorate([
  27490. BABYLON.serialize("backFaceCulling")
  27491. ], Material.prototype, "_backFaceCulling", void 0);
  27492. __decorate([
  27493. BABYLON.serialize()
  27494. ], Material.prototype, "sideOrientation", void 0);
  27495. __decorate([
  27496. BABYLON.serialize("alphaMode")
  27497. ], Material.prototype, "_alphaMode", void 0);
  27498. __decorate([
  27499. BABYLON.serialize()
  27500. ], Material.prototype, "_needDepthPrePass", void 0);
  27501. __decorate([
  27502. BABYLON.serialize()
  27503. ], Material.prototype, "disableDepthWrite", void 0);
  27504. __decorate([
  27505. BABYLON.serialize()
  27506. ], Material.prototype, "forceDepthWrite", void 0);
  27507. __decorate([
  27508. BABYLON.serialize()
  27509. ], Material.prototype, "separateCullingPass", void 0);
  27510. __decorate([
  27511. BABYLON.serialize("fogEnabled")
  27512. ], Material.prototype, "_fogEnabled", void 0);
  27513. __decorate([
  27514. BABYLON.serialize()
  27515. ], Material.prototype, "pointSize", void 0);
  27516. __decorate([
  27517. BABYLON.serialize()
  27518. ], Material.prototype, "zOffset", void 0);
  27519. __decorate([
  27520. BABYLON.serialize()
  27521. ], Material.prototype, "wireframe", null);
  27522. __decorate([
  27523. BABYLON.serialize()
  27524. ], Material.prototype, "pointsCloud", null);
  27525. __decorate([
  27526. BABYLON.serialize()
  27527. ], Material.prototype, "fillMode", null);
  27528. return Material;
  27529. }());
  27530. BABYLON.Material = Material;
  27531. })(BABYLON || (BABYLON = {}));
  27532. //# sourceMappingURL=babylon.material.js.map
  27533. var BABYLON;
  27534. (function (BABYLON) {
  27535. var UniformBuffer = /** @class */ (function () {
  27536. /**
  27537. * Uniform buffer objects.
  27538. *
  27539. * Handles blocks of uniform on the GPU.
  27540. *
  27541. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  27542. *
  27543. * For more information, please refer to :
  27544. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  27545. */
  27546. function UniformBuffer(engine, data, dynamic) {
  27547. this._engine = engine;
  27548. this._noUBO = !engine.supportsUniformBuffers;
  27549. this._dynamic = dynamic;
  27550. this._data = data || [];
  27551. this._uniformLocations = {};
  27552. this._uniformSizes = {};
  27553. this._uniformLocationPointer = 0;
  27554. this._needSync = false;
  27555. if (this._noUBO) {
  27556. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  27557. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  27558. this.updateFloat = this._updateFloatForEffect;
  27559. this.updateFloat2 = this._updateFloat2ForEffect;
  27560. this.updateFloat3 = this._updateFloat3ForEffect;
  27561. this.updateFloat4 = this._updateFloat4ForEffect;
  27562. this.updateMatrix = this._updateMatrixForEffect;
  27563. this.updateVector3 = this._updateVector3ForEffect;
  27564. this.updateVector4 = this._updateVector4ForEffect;
  27565. this.updateColor3 = this._updateColor3ForEffect;
  27566. this.updateColor4 = this._updateColor4ForEffect;
  27567. }
  27568. else {
  27569. this._engine._uniformBuffers.push(this);
  27570. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  27571. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  27572. this.updateFloat = this._updateFloatForUniform;
  27573. this.updateFloat2 = this._updateFloat2ForUniform;
  27574. this.updateFloat3 = this._updateFloat3ForUniform;
  27575. this.updateFloat4 = this._updateFloat4ForUniform;
  27576. this.updateMatrix = this._updateMatrixForUniform;
  27577. this.updateVector3 = this._updateVector3ForUniform;
  27578. this.updateVector4 = this._updateVector4ForUniform;
  27579. this.updateColor3 = this._updateColor3ForUniform;
  27580. this.updateColor4 = this._updateColor4ForUniform;
  27581. }
  27582. }
  27583. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  27584. // Properties
  27585. /**
  27586. * Indicates if the buffer is using the WebGL2 UBO implementation,
  27587. * or just falling back on setUniformXXX calls.
  27588. */
  27589. get: function () {
  27590. return !this._noUBO;
  27591. },
  27592. enumerable: true,
  27593. configurable: true
  27594. });
  27595. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  27596. /**
  27597. * Indicates if the WebGL underlying uniform buffer is in sync
  27598. * with the javascript cache data.
  27599. */
  27600. get: function () {
  27601. return !this._needSync;
  27602. },
  27603. enumerable: true,
  27604. configurable: true
  27605. });
  27606. /**
  27607. * Indicates if the WebGL underlying uniform buffer is dynamic.
  27608. * Also, a dynamic UniformBuffer will disable cache verification and always
  27609. * update the underlying WebGL uniform buffer to the GPU.
  27610. */
  27611. UniformBuffer.prototype.isDynamic = function () {
  27612. return this._dynamic !== undefined;
  27613. };
  27614. /**
  27615. * The data cache on JS side.
  27616. */
  27617. UniformBuffer.prototype.getData = function () {
  27618. return this._bufferData;
  27619. };
  27620. /**
  27621. * The underlying WebGL Uniform buffer.
  27622. */
  27623. UniformBuffer.prototype.getBuffer = function () {
  27624. return this._buffer;
  27625. };
  27626. /**
  27627. * std140 layout specifies how to align data within an UBO structure.
  27628. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  27629. * for specs.
  27630. */
  27631. UniformBuffer.prototype._fillAlignment = function (size) {
  27632. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  27633. // and 4x4 matrices
  27634. // TODO : change if other types are used
  27635. var alignment;
  27636. if (size <= 2) {
  27637. alignment = size;
  27638. }
  27639. else {
  27640. alignment = 4;
  27641. }
  27642. if ((this._uniformLocationPointer % alignment) !== 0) {
  27643. var oldPointer = this._uniformLocationPointer;
  27644. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  27645. var diff = this._uniformLocationPointer - oldPointer;
  27646. for (var i = 0; i < diff; i++) {
  27647. this._data.push(0);
  27648. }
  27649. }
  27650. };
  27651. /**
  27652. * Adds an uniform in the buffer.
  27653. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  27654. * for the layout to be correct !
  27655. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27656. * @param {number|number[]} size Data size, or data directly.
  27657. */
  27658. UniformBuffer.prototype.addUniform = function (name, size) {
  27659. if (this._noUBO) {
  27660. return;
  27661. }
  27662. if (this._uniformLocations[name] !== undefined) {
  27663. // Already existing uniform
  27664. return;
  27665. }
  27666. // This function must be called in the order of the shader layout !
  27667. // size can be the size of the uniform, or data directly
  27668. var data;
  27669. if (size instanceof Array) {
  27670. data = size;
  27671. size = data.length;
  27672. }
  27673. else {
  27674. size = size;
  27675. data = [];
  27676. // Fill with zeros
  27677. for (var i = 0; i < size; i++) {
  27678. data.push(0);
  27679. }
  27680. }
  27681. this._fillAlignment(size);
  27682. this._uniformSizes[name] = size;
  27683. this._uniformLocations[name] = this._uniformLocationPointer;
  27684. this._uniformLocationPointer += size;
  27685. for (var i = 0; i < size; i++) {
  27686. this._data.push(data[i]);
  27687. }
  27688. this._needSync = true;
  27689. };
  27690. /**
  27691. * Wrapper for addUniform.
  27692. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27693. * @param {Matrix} mat A 4x4 matrix.
  27694. */
  27695. UniformBuffer.prototype.addMatrix = function (name, mat) {
  27696. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  27697. };
  27698. /**
  27699. * Wrapper for addUniform.
  27700. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27701. * @param {number} x
  27702. * @param {number} y
  27703. */
  27704. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  27705. var temp = [x, y];
  27706. this.addUniform(name, temp);
  27707. };
  27708. /**
  27709. * Wrapper for addUniform.
  27710. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27711. * @param {number} x
  27712. * @param {number} y
  27713. * @param {number} z
  27714. */
  27715. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  27716. var temp = [x, y, z];
  27717. this.addUniform(name, temp);
  27718. };
  27719. /**
  27720. * Wrapper for addUniform.
  27721. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27722. * @param {Color3} color
  27723. */
  27724. UniformBuffer.prototype.addColor3 = function (name, color) {
  27725. var temp = new Array();
  27726. color.toArray(temp);
  27727. this.addUniform(name, temp);
  27728. };
  27729. /**
  27730. * Wrapper for addUniform.
  27731. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27732. * @param {Color3} color
  27733. * @param {number} alpha
  27734. */
  27735. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  27736. var temp = new Array();
  27737. color.toArray(temp);
  27738. temp.push(alpha);
  27739. this.addUniform(name, temp);
  27740. };
  27741. /**
  27742. * Wrapper for addUniform.
  27743. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27744. * @param {Vector3} vector
  27745. */
  27746. UniformBuffer.prototype.addVector3 = function (name, vector) {
  27747. var temp = new Array();
  27748. vector.toArray(temp);
  27749. this.addUniform(name, temp);
  27750. };
  27751. /**
  27752. * Wrapper for addUniform.
  27753. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27754. */
  27755. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  27756. this.addUniform(name, 12);
  27757. };
  27758. /**
  27759. * Wrapper for addUniform.
  27760. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27761. */
  27762. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  27763. this.addUniform(name, 8);
  27764. };
  27765. /**
  27766. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  27767. */
  27768. UniformBuffer.prototype.create = function () {
  27769. if (this._noUBO) {
  27770. return;
  27771. }
  27772. if (this._buffer) {
  27773. return; // nothing to do
  27774. }
  27775. // See spec, alignment must be filled as a vec4
  27776. this._fillAlignment(4);
  27777. this._bufferData = new Float32Array(this._data);
  27778. this._rebuild();
  27779. this._needSync = true;
  27780. };
  27781. UniformBuffer.prototype._rebuild = function () {
  27782. if (this._noUBO) {
  27783. return;
  27784. }
  27785. if (this._dynamic) {
  27786. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  27787. }
  27788. else {
  27789. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  27790. }
  27791. };
  27792. /**
  27793. * Updates the WebGL Uniform Buffer on the GPU.
  27794. * If the `dynamic` flag is set to true, no cache comparison is done.
  27795. * Otherwise, the buffer will be updated only if the cache differs.
  27796. */
  27797. UniformBuffer.prototype.update = function () {
  27798. if (!this._buffer) {
  27799. this.create();
  27800. return;
  27801. }
  27802. if (!this._dynamic && !this._needSync) {
  27803. return;
  27804. }
  27805. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  27806. this._needSync = false;
  27807. };
  27808. /**
  27809. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  27810. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27811. * @param {number[]|Float32Array} data Flattened data
  27812. * @param {number} size Size of the data.
  27813. */
  27814. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  27815. var location = this._uniformLocations[uniformName];
  27816. if (location === undefined) {
  27817. if (this._buffer) {
  27818. // Cannot add an uniform if the buffer is already created
  27819. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  27820. return;
  27821. }
  27822. this.addUniform(uniformName, size);
  27823. location = this._uniformLocations[uniformName];
  27824. }
  27825. if (!this._buffer) {
  27826. this.create();
  27827. }
  27828. if (!this._dynamic) {
  27829. // Cache for static uniform buffers
  27830. var changed = false;
  27831. for (var i = 0; i < size; i++) {
  27832. if (this._bufferData[location + i] !== data[i]) {
  27833. changed = true;
  27834. this._bufferData[location + i] = data[i];
  27835. }
  27836. }
  27837. this._needSync = this._needSync || changed;
  27838. }
  27839. else {
  27840. // No cache for dynamic
  27841. for (var i = 0; i < size; i++) {
  27842. this._bufferData[location + i] = data[i];
  27843. }
  27844. }
  27845. };
  27846. // Update methods
  27847. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  27848. // To match std140, matrix must be realigned
  27849. for (var i = 0; i < 3; i++) {
  27850. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  27851. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  27852. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  27853. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27854. }
  27855. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  27856. };
  27857. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  27858. this._currentEffect.setMatrix3x3(name, matrix);
  27859. };
  27860. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  27861. this._currentEffect.setMatrix2x2(name, matrix);
  27862. };
  27863. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  27864. // To match std140, matrix must be realigned
  27865. for (var i = 0; i < 2; i++) {
  27866. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  27867. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  27868. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  27869. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27870. }
  27871. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  27872. };
  27873. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  27874. this._currentEffect.setFloat(name, x);
  27875. };
  27876. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  27877. UniformBuffer._tempBuffer[0] = x;
  27878. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  27879. };
  27880. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  27881. if (suffix === void 0) { suffix = ""; }
  27882. this._currentEffect.setFloat2(name + suffix, x, y);
  27883. };
  27884. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  27885. if (suffix === void 0) { suffix = ""; }
  27886. UniformBuffer._tempBuffer[0] = x;
  27887. UniformBuffer._tempBuffer[1] = y;
  27888. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  27889. };
  27890. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  27891. if (suffix === void 0) { suffix = ""; }
  27892. this._currentEffect.setFloat3(name + suffix, x, y, z);
  27893. };
  27894. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  27895. if (suffix === void 0) { suffix = ""; }
  27896. UniformBuffer._tempBuffer[0] = x;
  27897. UniformBuffer._tempBuffer[1] = y;
  27898. UniformBuffer._tempBuffer[2] = z;
  27899. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27900. };
  27901. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  27902. if (suffix === void 0) { suffix = ""; }
  27903. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  27904. };
  27905. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  27906. if (suffix === void 0) { suffix = ""; }
  27907. UniformBuffer._tempBuffer[0] = x;
  27908. UniformBuffer._tempBuffer[1] = y;
  27909. UniformBuffer._tempBuffer[2] = z;
  27910. UniformBuffer._tempBuffer[3] = w;
  27911. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27912. };
  27913. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  27914. this._currentEffect.setMatrix(name, mat);
  27915. };
  27916. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  27917. this.updateUniform(name, mat.toArray(), 16);
  27918. };
  27919. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  27920. this._currentEffect.setVector3(name, vector);
  27921. };
  27922. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  27923. vector.toArray(UniformBuffer._tempBuffer);
  27924. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27925. };
  27926. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  27927. this._currentEffect.setVector4(name, vector);
  27928. };
  27929. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  27930. vector.toArray(UniformBuffer._tempBuffer);
  27931. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27932. };
  27933. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  27934. if (suffix === void 0) { suffix = ""; }
  27935. this._currentEffect.setColor3(name + suffix, color);
  27936. };
  27937. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  27938. if (suffix === void 0) { suffix = ""; }
  27939. color.toArray(UniformBuffer._tempBuffer);
  27940. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27941. };
  27942. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  27943. if (suffix === void 0) { suffix = ""; }
  27944. this._currentEffect.setColor4(name + suffix, color, alpha);
  27945. };
  27946. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  27947. if (suffix === void 0) { suffix = ""; }
  27948. color.toArray(UniformBuffer._tempBuffer);
  27949. UniformBuffer._tempBuffer[3] = alpha;
  27950. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27951. };
  27952. /**
  27953. * Sets a sampler uniform on the effect.
  27954. * @param {string} name Name of the sampler.
  27955. * @param {Texture} texture
  27956. */
  27957. UniformBuffer.prototype.setTexture = function (name, texture) {
  27958. this._currentEffect.setTexture(name, texture);
  27959. };
  27960. /**
  27961. * Directly updates the value of the uniform in the cache AND on the GPU.
  27962. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27963. * @param {number[]|Float32Array} data Flattened data
  27964. */
  27965. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  27966. this.updateUniform(uniformName, data, data.length);
  27967. this.update();
  27968. };
  27969. /**
  27970. * Binds this uniform buffer to an effect.
  27971. * @param {Effect} effect
  27972. * @param {string} name Name of the uniform block in the shader.
  27973. */
  27974. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  27975. this._currentEffect = effect;
  27976. if (this._noUBO || !this._buffer) {
  27977. return;
  27978. }
  27979. effect.bindUniformBuffer(this._buffer, name);
  27980. };
  27981. /**
  27982. * Disposes the uniform buffer.
  27983. */
  27984. UniformBuffer.prototype.dispose = function () {
  27985. if (this._noUBO) {
  27986. return;
  27987. }
  27988. var index = this._engine._uniformBuffers.indexOf(this);
  27989. if (index !== -1) {
  27990. this._engine._uniformBuffers.splice(index, 1);
  27991. }
  27992. if (!this._buffer) {
  27993. return;
  27994. }
  27995. if (this._engine._releaseBuffer(this._buffer)) {
  27996. this._buffer = null;
  27997. }
  27998. };
  27999. // Pool for avoiding memory leaks
  28000. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28001. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28002. return UniformBuffer;
  28003. }());
  28004. BABYLON.UniformBuffer = UniformBuffer;
  28005. })(BABYLON || (BABYLON = {}));
  28006. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28007. var BABYLON;
  28008. (function (BABYLON) {
  28009. var PushMaterial = /** @class */ (function (_super) {
  28010. __extends(PushMaterial, _super);
  28011. function PushMaterial(name, scene) {
  28012. var _this = _super.call(this, name, scene) || this;
  28013. _this.storeEffectOnSubMeshes = true;
  28014. return _this;
  28015. }
  28016. PushMaterial.prototype.getEffect = function () {
  28017. return this._activeEffect;
  28018. };
  28019. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  28020. if (!mesh) {
  28021. return false;
  28022. }
  28023. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  28024. return true;
  28025. }
  28026. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  28027. };
  28028. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28029. this._activeEffect.setMatrix("world", world);
  28030. };
  28031. PushMaterial.prototype.bind = function (world, mesh) {
  28032. if (!mesh) {
  28033. return;
  28034. }
  28035. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  28036. };
  28037. PushMaterial.prototype._afterBind = function (mesh, effect) {
  28038. if (effect === void 0) { effect = null; }
  28039. _super.prototype._afterBind.call(this, mesh);
  28040. this.getScene()._cachedEffect = effect;
  28041. };
  28042. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  28043. if (visibility === void 0) { visibility = 1; }
  28044. return scene.isCachedMaterialInvalid(this, effect, visibility);
  28045. };
  28046. return PushMaterial;
  28047. }(BABYLON.Material));
  28048. BABYLON.PushMaterial = PushMaterial;
  28049. })(BABYLON || (BABYLON = {}));
  28050. //# sourceMappingURL=babylon.pushMaterial.js.map
  28051. var BABYLON;
  28052. (function (BABYLON) {
  28053. var VertexData = /** @class */ (function () {
  28054. function VertexData() {
  28055. }
  28056. VertexData.prototype.set = function (data, kind) {
  28057. switch (kind) {
  28058. case BABYLON.VertexBuffer.PositionKind:
  28059. this.positions = data;
  28060. break;
  28061. case BABYLON.VertexBuffer.NormalKind:
  28062. this.normals = data;
  28063. break;
  28064. case BABYLON.VertexBuffer.TangentKind:
  28065. this.tangents = data;
  28066. break;
  28067. case BABYLON.VertexBuffer.UVKind:
  28068. this.uvs = data;
  28069. break;
  28070. case BABYLON.VertexBuffer.UV2Kind:
  28071. this.uvs2 = data;
  28072. break;
  28073. case BABYLON.VertexBuffer.UV3Kind:
  28074. this.uvs3 = data;
  28075. break;
  28076. case BABYLON.VertexBuffer.UV4Kind:
  28077. this.uvs4 = data;
  28078. break;
  28079. case BABYLON.VertexBuffer.UV5Kind:
  28080. this.uvs5 = data;
  28081. break;
  28082. case BABYLON.VertexBuffer.UV6Kind:
  28083. this.uvs6 = data;
  28084. break;
  28085. case BABYLON.VertexBuffer.ColorKind:
  28086. this.colors = data;
  28087. break;
  28088. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28089. this.matricesIndices = data;
  28090. break;
  28091. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28092. this.matricesWeights = data;
  28093. break;
  28094. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28095. this.matricesIndicesExtra = data;
  28096. break;
  28097. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28098. this.matricesWeightsExtra = data;
  28099. break;
  28100. }
  28101. };
  28102. /**
  28103. * Associates the vertexData to the passed Mesh.
  28104. * Sets it as updatable or not (default `false`).
  28105. * Returns the VertexData.
  28106. */
  28107. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28108. this._applyTo(mesh, updatable);
  28109. return this;
  28110. };
  28111. /**
  28112. * Associates the vertexData to the passed Geometry.
  28113. * Sets it as updatable or not (default `false`).
  28114. * Returns the VertexData.
  28115. */
  28116. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28117. this._applyTo(geometry, updatable);
  28118. return this;
  28119. };
  28120. /**
  28121. * Updates the associated mesh.
  28122. * Returns the VertexData.
  28123. */
  28124. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28125. this._update(mesh);
  28126. return this;
  28127. };
  28128. /**
  28129. * Updates the associated geometry.
  28130. * Returns the VertexData.
  28131. */
  28132. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28133. this._update(geometry);
  28134. return this;
  28135. };
  28136. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28137. if (updatable === void 0) { updatable = false; }
  28138. if (this.positions) {
  28139. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28140. }
  28141. if (this.normals) {
  28142. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28143. }
  28144. if (this.tangents) {
  28145. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28146. }
  28147. if (this.uvs) {
  28148. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28149. }
  28150. if (this.uvs2) {
  28151. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28152. }
  28153. if (this.uvs3) {
  28154. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28155. }
  28156. if (this.uvs4) {
  28157. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28158. }
  28159. if (this.uvs5) {
  28160. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28161. }
  28162. if (this.uvs6) {
  28163. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28164. }
  28165. if (this.colors) {
  28166. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28167. }
  28168. if (this.matricesIndices) {
  28169. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28170. }
  28171. if (this.matricesWeights) {
  28172. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28173. }
  28174. if (this.matricesIndicesExtra) {
  28175. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28176. }
  28177. if (this.matricesWeightsExtra) {
  28178. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28179. }
  28180. if (this.indices) {
  28181. meshOrGeometry.setIndices(this.indices, null, updatable);
  28182. }
  28183. return this;
  28184. };
  28185. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28186. if (this.positions) {
  28187. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28188. }
  28189. if (this.normals) {
  28190. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28191. }
  28192. if (this.tangents) {
  28193. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28194. }
  28195. if (this.uvs) {
  28196. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28197. }
  28198. if (this.uvs2) {
  28199. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28200. }
  28201. if (this.uvs3) {
  28202. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28203. }
  28204. if (this.uvs4) {
  28205. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28206. }
  28207. if (this.uvs5) {
  28208. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28209. }
  28210. if (this.uvs6) {
  28211. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28212. }
  28213. if (this.colors) {
  28214. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28215. }
  28216. if (this.matricesIndices) {
  28217. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28218. }
  28219. if (this.matricesWeights) {
  28220. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28221. }
  28222. if (this.matricesIndicesExtra) {
  28223. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28224. }
  28225. if (this.matricesWeightsExtra) {
  28226. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28227. }
  28228. if (this.indices) {
  28229. meshOrGeometry.setIndices(this.indices, null);
  28230. }
  28231. return this;
  28232. };
  28233. /**
  28234. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28235. * Returns the VertexData.
  28236. */
  28237. VertexData.prototype.transform = function (matrix) {
  28238. var transformed = BABYLON.Vector3.Zero();
  28239. var index;
  28240. if (this.positions) {
  28241. var position = BABYLON.Vector3.Zero();
  28242. for (index = 0; index < this.positions.length; index += 3) {
  28243. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28244. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28245. this.positions[index] = transformed.x;
  28246. this.positions[index + 1] = transformed.y;
  28247. this.positions[index + 2] = transformed.z;
  28248. }
  28249. }
  28250. if (this.normals) {
  28251. var normal = BABYLON.Vector3.Zero();
  28252. for (index = 0; index < this.normals.length; index += 3) {
  28253. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28254. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28255. this.normals[index] = transformed.x;
  28256. this.normals[index + 1] = transformed.y;
  28257. this.normals[index + 2] = transformed.z;
  28258. }
  28259. }
  28260. if (this.tangents) {
  28261. var tangent = BABYLON.Vector4.Zero();
  28262. var tangentTransformed = BABYLON.Vector4.Zero();
  28263. for (index = 0; index < this.tangents.length; index += 4) {
  28264. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28265. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28266. this.tangents[index] = tangentTransformed.x;
  28267. this.tangents[index + 1] = tangentTransformed.y;
  28268. this.tangents[index + 2] = tangentTransformed.z;
  28269. this.tangents[index + 3] = tangentTransformed.w;
  28270. }
  28271. }
  28272. return this;
  28273. };
  28274. /**
  28275. * Merges the passed VertexData into the current one.
  28276. * Returns the modified VertexData.
  28277. */
  28278. VertexData.prototype.merge = function (other, options) {
  28279. options = options || {};
  28280. if (other.indices) {
  28281. if (!this.indices) {
  28282. this.indices = [];
  28283. }
  28284. var offset = this.positions ? this.positions.length / 3 : 0;
  28285. for (var index = 0; index < other.indices.length; index++) {
  28286. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28287. this.indices.push(other.indices[index] + offset);
  28288. }
  28289. }
  28290. this.positions = this._mergeElement(this.positions, other.positions);
  28291. if (!this.positions) {
  28292. return this;
  28293. }
  28294. var count = this.positions.length / 3;
  28295. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28296. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28297. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28298. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28299. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28300. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28301. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28302. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28303. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28304. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28305. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28306. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28307. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28308. return this;
  28309. };
  28310. VertexData.prototype._mergeElement = function (source, other, length) {
  28311. if (length === void 0) { length = 0; }
  28312. if (!other && !source) {
  28313. return null;
  28314. }
  28315. if (!other) {
  28316. return this._mergeElement(source, new Float32Array(source.length), length);
  28317. }
  28318. if (!source) {
  28319. if (length === 0 || length === other.length) {
  28320. return other;
  28321. }
  28322. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28323. }
  28324. var len = other.length + source.length;
  28325. var isSrcTypedArray = source instanceof Float32Array;
  28326. var isOthTypedArray = other instanceof Float32Array;
  28327. // use non-loop method when the source is Float32Array
  28328. if (isSrcTypedArray) {
  28329. var ret32 = new Float32Array(len);
  28330. ret32.set(source);
  28331. ret32.set(other, source.length);
  28332. return ret32;
  28333. // source is number[], when other is also use concat
  28334. }
  28335. else if (!isOthTypedArray) {
  28336. return source.concat(other);
  28337. // source is a number[], but other is a Float32Array, loop required
  28338. }
  28339. else {
  28340. var ret = source.slice(0); // copy source to a separate array
  28341. for (var i = 0, len = other.length; i < len; i++) {
  28342. ret.push(other[i]);
  28343. }
  28344. return ret;
  28345. }
  28346. };
  28347. /**
  28348. * Serializes the VertexData.
  28349. * Returns a serialized object.
  28350. */
  28351. VertexData.prototype.serialize = function () {
  28352. var serializationObject = this.serialize();
  28353. if (this.positions) {
  28354. serializationObject.positions = this.positions;
  28355. }
  28356. if (this.normals) {
  28357. serializationObject.normals = this.normals;
  28358. }
  28359. if (this.tangents) {
  28360. serializationObject.tangents = this.tangents;
  28361. }
  28362. if (this.uvs) {
  28363. serializationObject.uvs = this.uvs;
  28364. }
  28365. if (this.uvs2) {
  28366. serializationObject.uvs2 = this.uvs2;
  28367. }
  28368. if (this.uvs3) {
  28369. serializationObject.uvs3 = this.uvs3;
  28370. }
  28371. if (this.uvs4) {
  28372. serializationObject.uvs4 = this.uvs4;
  28373. }
  28374. if (this.uvs5) {
  28375. serializationObject.uvs5 = this.uvs5;
  28376. }
  28377. if (this.uvs6) {
  28378. serializationObject.uvs6 = this.uvs6;
  28379. }
  28380. if (this.colors) {
  28381. serializationObject.colors = this.colors;
  28382. }
  28383. if (this.matricesIndices) {
  28384. serializationObject.matricesIndices = this.matricesIndices;
  28385. serializationObject.matricesIndices._isExpanded = true;
  28386. }
  28387. if (this.matricesWeights) {
  28388. serializationObject.matricesWeights = this.matricesWeights;
  28389. }
  28390. if (this.matricesIndicesExtra) {
  28391. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28392. serializationObject.matricesIndicesExtra._isExpanded = true;
  28393. }
  28394. if (this.matricesWeightsExtra) {
  28395. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28396. }
  28397. serializationObject.indices = this.indices;
  28398. return serializationObject;
  28399. };
  28400. // Statics
  28401. /**
  28402. * Returns the object VertexData associated to the passed mesh.
  28403. */
  28404. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28405. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28406. };
  28407. /**
  28408. * Returns the object VertexData associated to the passed geometry.
  28409. */
  28410. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28411. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28412. };
  28413. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28414. var result = new VertexData();
  28415. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28416. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28417. }
  28418. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28419. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28420. }
  28421. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28422. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28423. }
  28424. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28425. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28426. }
  28427. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28428. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28429. }
  28430. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28431. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28432. }
  28433. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28434. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28435. }
  28436. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28437. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28438. }
  28439. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28440. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28441. }
  28442. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28443. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28444. }
  28445. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28446. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28447. }
  28448. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28449. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28450. }
  28451. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28452. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28453. }
  28454. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28455. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28456. }
  28457. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28458. return result;
  28459. };
  28460. /**
  28461. * Creates the vertexData of the Ribbon.
  28462. */
  28463. VertexData.CreateRibbon = function (options) {
  28464. var pathArray = options.pathArray;
  28465. var closeArray = options.closeArray || false;
  28466. var closePath = options.closePath || false;
  28467. var invertUV = options.invertUV || false;
  28468. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28469. var offset = options.offset || defaultOffset;
  28470. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28471. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28472. var customUV = options.uvs;
  28473. var customColors = options.colors;
  28474. var positions = [];
  28475. var indices = [];
  28476. var normals = [];
  28477. var uvs = [];
  28478. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28479. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28480. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28481. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28482. var minlg; // minimal length among all paths from pathArray
  28483. var lg = []; // array of path lengths : nb of vertex per path
  28484. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28485. var p; // path iterator
  28486. var i; // point iterator
  28487. var j; // point iterator
  28488. // if single path in pathArray
  28489. if (pathArray.length < 2) {
  28490. var ar1 = [];
  28491. var ar2 = [];
  28492. for (i = 0; i < pathArray[0].length - offset; i++) {
  28493. ar1.push(pathArray[0][i]);
  28494. ar2.push(pathArray[0][i + offset]);
  28495. }
  28496. pathArray = [ar1, ar2];
  28497. }
  28498. // positions and horizontal distances (u)
  28499. var idc = 0;
  28500. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  28501. var path;
  28502. var l;
  28503. minlg = pathArray[0].length;
  28504. var vectlg;
  28505. var dist;
  28506. for (p = 0; p < pathArray.length; p++) {
  28507. uTotalDistance[p] = 0;
  28508. us[p] = [0];
  28509. path = pathArray[p];
  28510. l = path.length;
  28511. minlg = (minlg < l) ? minlg : l;
  28512. j = 0;
  28513. while (j < l) {
  28514. positions.push(path[j].x, path[j].y, path[j].z);
  28515. if (j > 0) {
  28516. vectlg = path[j].subtract(path[j - 1]).length();
  28517. dist = vectlg + uTotalDistance[p];
  28518. us[p].push(dist);
  28519. uTotalDistance[p] = dist;
  28520. }
  28521. j++;
  28522. }
  28523. if (closePath) {
  28524. j--;
  28525. positions.push(path[0].x, path[0].y, path[0].z);
  28526. vectlg = path[j].subtract(path[0]).length();
  28527. dist = vectlg + uTotalDistance[p];
  28528. us[p].push(dist);
  28529. uTotalDistance[p] = dist;
  28530. }
  28531. lg[p] = l + closePathCorr;
  28532. idx[p] = idc;
  28533. idc += (l + closePathCorr);
  28534. }
  28535. // vertical distances (v)
  28536. var path1;
  28537. var path2;
  28538. var vertex1 = null;
  28539. var vertex2 = null;
  28540. for (i = 0; i < minlg + closePathCorr; i++) {
  28541. vTotalDistance[i] = 0;
  28542. vs[i] = [0];
  28543. for (p = 0; p < pathArray.length - 1; p++) {
  28544. path1 = pathArray[p];
  28545. path2 = pathArray[p + 1];
  28546. if (i === minlg) {
  28547. vertex1 = path1[0];
  28548. vertex2 = path2[0];
  28549. }
  28550. else {
  28551. vertex1 = path1[i];
  28552. vertex2 = path2[i];
  28553. }
  28554. vectlg = vertex2.subtract(vertex1).length();
  28555. dist = vectlg + vTotalDistance[i];
  28556. vs[i].push(dist);
  28557. vTotalDistance[i] = dist;
  28558. }
  28559. if (closeArray && vertex2 && vertex1) {
  28560. path1 = pathArray[p];
  28561. path2 = pathArray[0];
  28562. if (i === minlg) {
  28563. vertex2 = path2[0];
  28564. }
  28565. vectlg = vertex2.subtract(vertex1).length();
  28566. dist = vectlg + vTotalDistance[i];
  28567. vTotalDistance[i] = dist;
  28568. }
  28569. }
  28570. // uvs
  28571. var u;
  28572. var v;
  28573. if (customUV) {
  28574. for (p = 0; p < customUV.length; p++) {
  28575. uvs.push(customUV[p].x, customUV[p].y);
  28576. }
  28577. }
  28578. else {
  28579. for (p = 0; p < pathArray.length; p++) {
  28580. for (i = 0; i < minlg + closePathCorr; i++) {
  28581. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  28582. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  28583. if (invertUV) {
  28584. uvs.push(v, u);
  28585. }
  28586. else {
  28587. uvs.push(u, v);
  28588. }
  28589. }
  28590. }
  28591. }
  28592. // indices
  28593. p = 0; // path index
  28594. var pi = 0; // positions array index
  28595. var l1 = lg[p] - 1; // path1 length
  28596. var l2 = lg[p + 1] - 1; // path2 length
  28597. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28598. var shft = idx[1] - idx[0]; // shift
  28599. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28600. while (pi <= min && p < path1nb) {
  28601. // 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
  28602. indices.push(pi, pi + shft, pi + 1);
  28603. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28604. pi += 1;
  28605. if (pi === min) {
  28606. p++;
  28607. if (p === lg.length - 1) {
  28608. shft = idx[0] - idx[p];
  28609. l1 = lg[p] - 1;
  28610. l2 = lg[0] - 1;
  28611. }
  28612. else {
  28613. shft = idx[p + 1] - idx[p];
  28614. l1 = lg[p] - 1;
  28615. l2 = lg[p + 1] - 1;
  28616. }
  28617. pi = idx[p];
  28618. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28619. }
  28620. }
  28621. // normals
  28622. VertexData.ComputeNormals(positions, indices, normals);
  28623. if (closePath) {
  28624. var indexFirst = 0;
  28625. var indexLast = 0;
  28626. for (p = 0; p < pathArray.length; p++) {
  28627. indexFirst = idx[p] * 3;
  28628. if (p + 1 < pathArray.length) {
  28629. indexLast = (idx[p + 1] - 1) * 3;
  28630. }
  28631. else {
  28632. indexLast = normals.length - 3;
  28633. }
  28634. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28635. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28636. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28637. normals[indexLast] = normals[indexFirst];
  28638. normals[indexLast + 1] = normals[indexFirst + 1];
  28639. normals[indexLast + 2] = normals[indexFirst + 2];
  28640. }
  28641. }
  28642. // sides
  28643. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28644. // Colors
  28645. var colors = null;
  28646. if (customColors) {
  28647. colors = new Float32Array(customColors.length * 4);
  28648. for (var c = 0; c < customColors.length; c++) {
  28649. colors[c * 4] = customColors[c].r;
  28650. colors[c * 4 + 1] = customColors[c].g;
  28651. colors[c * 4 + 2] = customColors[c].b;
  28652. colors[c * 4 + 3] = customColors[c].a;
  28653. }
  28654. }
  28655. // Result
  28656. var vertexData = new VertexData();
  28657. var positions32 = new Float32Array(positions);
  28658. var normals32 = new Float32Array(normals);
  28659. var uvs32 = new Float32Array(uvs);
  28660. vertexData.indices = indices;
  28661. vertexData.positions = positions32;
  28662. vertexData.normals = normals32;
  28663. vertexData.uvs = uvs32;
  28664. if (colors) {
  28665. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  28666. }
  28667. if (closePath) {
  28668. vertexData._idx = idx;
  28669. }
  28670. return vertexData;
  28671. };
  28672. /**
  28673. * Creates the VertexData of the Box.
  28674. */
  28675. VertexData.CreateBox = function (options) {
  28676. var normalsSource = [
  28677. new BABYLON.Vector3(0, 0, 1),
  28678. new BABYLON.Vector3(0, 0, -1),
  28679. new BABYLON.Vector3(1, 0, 0),
  28680. new BABYLON.Vector3(-1, 0, 0),
  28681. new BABYLON.Vector3(0, 1, 0),
  28682. new BABYLON.Vector3(0, -1, 0)
  28683. ];
  28684. var indices = [];
  28685. var positions = [];
  28686. var normals = [];
  28687. var uvs = [];
  28688. var width = options.width || options.size || 1;
  28689. var height = options.height || options.size || 1;
  28690. var depth = options.depth || options.size || 1;
  28691. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28692. var faceUV = options.faceUV || new Array(6);
  28693. var faceColors = options.faceColors;
  28694. var colors = [];
  28695. // default face colors and UV if undefined
  28696. for (var f = 0; f < 6; f++) {
  28697. if (faceUV[f] === undefined) {
  28698. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28699. }
  28700. if (faceColors && faceColors[f] === undefined) {
  28701. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28702. }
  28703. }
  28704. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28705. // Create each face in turn.
  28706. for (var index = 0; index < normalsSource.length; index++) {
  28707. var normal = normalsSource[index];
  28708. // Get two vectors perpendicular to the face normal and to each other.
  28709. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28710. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28711. // Six indices (two triangles) per face.
  28712. var verticesLength = positions.length / 3;
  28713. indices.push(verticesLength);
  28714. indices.push(verticesLength + 1);
  28715. indices.push(verticesLength + 2);
  28716. indices.push(verticesLength);
  28717. indices.push(verticesLength + 2);
  28718. indices.push(verticesLength + 3);
  28719. // Four vertices per face.
  28720. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28721. positions.push(vertex.x, vertex.y, vertex.z);
  28722. normals.push(normal.x, normal.y, normal.z);
  28723. uvs.push(faceUV[index].z, faceUV[index].w);
  28724. if (faceColors) {
  28725. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28726. }
  28727. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28728. positions.push(vertex.x, vertex.y, vertex.z);
  28729. normals.push(normal.x, normal.y, normal.z);
  28730. uvs.push(faceUV[index].x, faceUV[index].w);
  28731. if (faceColors) {
  28732. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28733. }
  28734. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28735. positions.push(vertex.x, vertex.y, vertex.z);
  28736. normals.push(normal.x, normal.y, normal.z);
  28737. uvs.push(faceUV[index].x, faceUV[index].y);
  28738. if (faceColors) {
  28739. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28740. }
  28741. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28742. positions.push(vertex.x, vertex.y, vertex.z);
  28743. normals.push(normal.x, normal.y, normal.z);
  28744. uvs.push(faceUV[index].z, faceUV[index].y);
  28745. if (faceColors) {
  28746. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28747. }
  28748. }
  28749. // sides
  28750. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28751. // Result
  28752. var vertexData = new VertexData();
  28753. vertexData.indices = indices;
  28754. vertexData.positions = positions;
  28755. vertexData.normals = normals;
  28756. vertexData.uvs = uvs;
  28757. if (faceColors) {
  28758. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28759. vertexData.colors = totalColors;
  28760. }
  28761. return vertexData;
  28762. };
  28763. /**
  28764. * Creates the VertexData of the Sphere.
  28765. */
  28766. VertexData.CreateSphere = function (options) {
  28767. var segments = options.segments || 32;
  28768. var diameterX = options.diameterX || options.diameter || 1;
  28769. var diameterY = options.diameterY || options.diameter || 1;
  28770. var diameterZ = options.diameterZ || options.diameter || 1;
  28771. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28772. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28773. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28774. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28775. var totalZRotationSteps = 2 + segments;
  28776. var totalYRotationSteps = 2 * totalZRotationSteps;
  28777. var indices = [];
  28778. var positions = [];
  28779. var normals = [];
  28780. var uvs = [];
  28781. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28782. var normalizedZ = zRotationStep / totalZRotationSteps;
  28783. var angleZ = normalizedZ * Math.PI * slice;
  28784. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28785. var normalizedY = yRotationStep / totalYRotationSteps;
  28786. var angleY = normalizedY * Math.PI * 2 * arc;
  28787. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28788. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28789. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28790. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28791. var vertex = complete.multiply(radius);
  28792. var normal = complete.divide(radius).normalize();
  28793. positions.push(vertex.x, vertex.y, vertex.z);
  28794. normals.push(normal.x, normal.y, normal.z);
  28795. uvs.push(normalizedY, normalizedZ);
  28796. }
  28797. if (zRotationStep > 0) {
  28798. var verticesCount = positions.length / 3;
  28799. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28800. indices.push((firstIndex));
  28801. indices.push((firstIndex + 1));
  28802. indices.push(firstIndex + totalYRotationSteps + 1);
  28803. indices.push((firstIndex + totalYRotationSteps + 1));
  28804. indices.push((firstIndex + 1));
  28805. indices.push((firstIndex + totalYRotationSteps + 2));
  28806. }
  28807. }
  28808. }
  28809. // Sides
  28810. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28811. // Result
  28812. var vertexData = new VertexData();
  28813. vertexData.indices = indices;
  28814. vertexData.positions = positions;
  28815. vertexData.normals = normals;
  28816. vertexData.uvs = uvs;
  28817. return vertexData;
  28818. };
  28819. /**
  28820. * Creates the VertexData of the Cylinder or Cone.
  28821. */
  28822. VertexData.CreateCylinder = function (options) {
  28823. var height = options.height || 2;
  28824. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28825. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  28826. var tessellation = options.tessellation || 24;
  28827. var subdivisions = options.subdivisions || 1;
  28828. var hasRings = options.hasRings ? true : false;
  28829. var enclose = options.enclose ? true : false;
  28830. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28831. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28832. var faceUV = options.faceUV || new Array(3);
  28833. var faceColors = options.faceColors;
  28834. // default face colors and UV if undefined
  28835. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28836. var ringNb = (hasRings) ? subdivisions : 1;
  28837. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28838. var f;
  28839. for (f = 0; f < surfaceNb; f++) {
  28840. if (faceColors && faceColors[f] === undefined) {
  28841. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28842. }
  28843. }
  28844. for (f = 0; f < surfaceNb; f++) {
  28845. if (faceUV && faceUV[f] === undefined) {
  28846. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28847. }
  28848. }
  28849. var indices = new Array();
  28850. var positions = new Array();
  28851. var normals = new Array();
  28852. var uvs = new Array();
  28853. var colors = new Array();
  28854. var angle_step = Math.PI * 2 * arc / tessellation;
  28855. var angle;
  28856. var h;
  28857. var radius;
  28858. var tan = (diameterBottom - diameterTop) / 2 / height;
  28859. var ringVertex = BABYLON.Vector3.Zero();
  28860. var ringNormal = BABYLON.Vector3.Zero();
  28861. var ringFirstVertex = BABYLON.Vector3.Zero();
  28862. var ringFirstNormal = BABYLON.Vector3.Zero();
  28863. var quadNormal = BABYLON.Vector3.Zero();
  28864. var Y = BABYLON.Axis.Y;
  28865. // positions, normals, uvs
  28866. var i;
  28867. var j;
  28868. var r;
  28869. var ringIdx = 1;
  28870. var s = 1; // surface index
  28871. var cs = 0;
  28872. var v = 0;
  28873. for (i = 0; i <= subdivisions; i++) {
  28874. h = i / subdivisions;
  28875. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28876. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28877. for (r = 0; r < ringIdx; r++) {
  28878. if (hasRings) {
  28879. s += r;
  28880. }
  28881. if (enclose) {
  28882. s += 2 * r;
  28883. }
  28884. for (j = 0; j <= tessellation; j++) {
  28885. angle = j * angle_step;
  28886. // position
  28887. ringVertex.x = Math.cos(-angle) * radius;
  28888. ringVertex.y = -height / 2 + h * height;
  28889. ringVertex.z = Math.sin(-angle) * radius;
  28890. // normal
  28891. if (diameterTop === 0 && i === subdivisions) {
  28892. // if no top cap, reuse former normals
  28893. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28894. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28895. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28896. }
  28897. else {
  28898. ringNormal.x = ringVertex.x;
  28899. ringNormal.z = ringVertex.z;
  28900. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28901. ringNormal.normalize();
  28902. }
  28903. // keep first ring vertex values for enclose
  28904. if (j === 0) {
  28905. ringFirstVertex.copyFrom(ringVertex);
  28906. ringFirstNormal.copyFrom(ringNormal);
  28907. }
  28908. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28909. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28910. if (hasRings) {
  28911. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28912. }
  28913. else {
  28914. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28915. }
  28916. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28917. if (faceColors) {
  28918. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28919. }
  28920. }
  28921. // if enclose, add four vertices and their dedicated normals
  28922. if (arc !== 1 && enclose) {
  28923. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28924. positions.push(0, ringVertex.y, 0);
  28925. positions.push(0, ringVertex.y, 0);
  28926. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28927. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28928. quadNormal.normalize();
  28929. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28930. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28931. quadNormal.normalize();
  28932. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28933. if (hasRings) {
  28934. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28935. }
  28936. else {
  28937. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28938. }
  28939. uvs.push(faceUV[s + 1].x, v);
  28940. uvs.push(faceUV[s + 1].z, v);
  28941. if (hasRings) {
  28942. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28943. }
  28944. else {
  28945. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28946. }
  28947. uvs.push(faceUV[s + 2].x, v);
  28948. uvs.push(faceUV[s + 2].z, v);
  28949. if (faceColors) {
  28950. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28951. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28952. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28953. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28954. }
  28955. }
  28956. if (cs !== s) {
  28957. cs = s;
  28958. }
  28959. }
  28960. }
  28961. // indices
  28962. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28963. var s;
  28964. i = 0;
  28965. for (s = 0; s < subdivisions; s++) {
  28966. var i0 = 0;
  28967. var i1 = 0;
  28968. var i2 = 0;
  28969. var i3 = 0;
  28970. for (j = 0; j < tessellation; j++) {
  28971. i0 = i * (e + 1) + j;
  28972. i1 = (i + 1) * (e + 1) + j;
  28973. i2 = i * (e + 1) + (j + 1);
  28974. i3 = (i + 1) * (e + 1) + (j + 1);
  28975. indices.push(i0, i1, i2);
  28976. indices.push(i3, i2, i1);
  28977. }
  28978. if (arc !== 1 && enclose) {
  28979. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28980. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28981. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28982. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28983. }
  28984. i = (hasRings) ? (i + 2) : (i + 1);
  28985. }
  28986. // Caps
  28987. var createCylinderCap = function (isTop) {
  28988. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28989. if (radius === 0) {
  28990. return;
  28991. }
  28992. // Cap positions, normals & uvs
  28993. var angle;
  28994. var circleVector;
  28995. var i;
  28996. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28997. var c = null;
  28998. if (faceColors) {
  28999. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29000. }
  29001. // cap center
  29002. var vbase = positions.length / 3;
  29003. var offset = isTop ? height / 2 : -height / 2;
  29004. var center = new BABYLON.Vector3(0, offset, 0);
  29005. positions.push(center.x, center.y, center.z);
  29006. normals.push(0, isTop ? 1 : -1, 0);
  29007. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29008. if (c) {
  29009. colors.push(c.r, c.g, c.b, c.a);
  29010. }
  29011. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29012. for (i = 0; i <= tessellation; i++) {
  29013. angle = Math.PI * 2 * i * arc / tessellation;
  29014. var cos = Math.cos(-angle);
  29015. var sin = Math.sin(-angle);
  29016. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29017. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29018. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29019. normals.push(0, isTop ? 1 : -1, 0);
  29020. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29021. if (c) {
  29022. colors.push(c.r, c.g, c.b, c.a);
  29023. }
  29024. }
  29025. // Cap indices
  29026. for (i = 0; i < tessellation; i++) {
  29027. if (!isTop) {
  29028. indices.push(vbase);
  29029. indices.push(vbase + (i + 1));
  29030. indices.push(vbase + (i + 2));
  29031. }
  29032. else {
  29033. indices.push(vbase);
  29034. indices.push(vbase + (i + 2));
  29035. indices.push(vbase + (i + 1));
  29036. }
  29037. }
  29038. };
  29039. // add caps to geometry
  29040. createCylinderCap(false);
  29041. createCylinderCap(true);
  29042. // Sides
  29043. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29044. var vertexData = new VertexData();
  29045. vertexData.indices = indices;
  29046. vertexData.positions = positions;
  29047. vertexData.normals = normals;
  29048. vertexData.uvs = uvs;
  29049. if (faceColors) {
  29050. vertexData.colors = colors;
  29051. }
  29052. return vertexData;
  29053. };
  29054. /**
  29055. * Creates the VertexData of the Torus.
  29056. */
  29057. VertexData.CreateTorus = function (options) {
  29058. var indices = [];
  29059. var positions = [];
  29060. var normals = [];
  29061. var uvs = [];
  29062. var diameter = options.diameter || 1;
  29063. var thickness = options.thickness || 0.5;
  29064. var tessellation = options.tessellation || 16;
  29065. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29066. var stride = tessellation + 1;
  29067. for (var i = 0; i <= tessellation; i++) {
  29068. var u = i / tessellation;
  29069. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29070. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29071. for (var j = 0; j <= tessellation; j++) {
  29072. var v = 1 - j / tessellation;
  29073. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29074. var dx = Math.cos(innerAngle);
  29075. var dy = Math.sin(innerAngle);
  29076. // Create a vertex.
  29077. var normal = new BABYLON.Vector3(dx, dy, 0);
  29078. var position = normal.scale(thickness / 2);
  29079. var textureCoordinate = new BABYLON.Vector2(u, v);
  29080. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29081. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29082. positions.push(position.x, position.y, position.z);
  29083. normals.push(normal.x, normal.y, normal.z);
  29084. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29085. // And create indices for two triangles.
  29086. var nextI = (i + 1) % stride;
  29087. var nextJ = (j + 1) % stride;
  29088. indices.push(i * stride + j);
  29089. indices.push(i * stride + nextJ);
  29090. indices.push(nextI * stride + j);
  29091. indices.push(i * stride + nextJ);
  29092. indices.push(nextI * stride + nextJ);
  29093. indices.push(nextI * stride + j);
  29094. }
  29095. }
  29096. // Sides
  29097. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29098. // Result
  29099. var vertexData = new VertexData();
  29100. vertexData.indices = indices;
  29101. vertexData.positions = positions;
  29102. vertexData.normals = normals;
  29103. vertexData.uvs = uvs;
  29104. return vertexData;
  29105. };
  29106. /**
  29107. * Creates the VertexData of the LineSystem.
  29108. */
  29109. VertexData.CreateLineSystem = function (options) {
  29110. var indices = [];
  29111. var positions = [];
  29112. var lines = options.lines;
  29113. var idx = 0;
  29114. for (var l = 0; l < lines.length; l++) {
  29115. var points = lines[l];
  29116. for (var index = 0; index < points.length; index++) {
  29117. positions.push(points[index].x, points[index].y, points[index].z);
  29118. if (index > 0) {
  29119. indices.push(idx - 1);
  29120. indices.push(idx);
  29121. }
  29122. idx++;
  29123. }
  29124. }
  29125. var vertexData = new VertexData();
  29126. vertexData.indices = indices;
  29127. vertexData.positions = positions;
  29128. return vertexData;
  29129. };
  29130. /**
  29131. * Create the VertexData of the DashedLines.
  29132. */
  29133. VertexData.CreateDashedLines = function (options) {
  29134. var dashSize = options.dashSize || 3;
  29135. var gapSize = options.gapSize || 1;
  29136. var dashNb = options.dashNb || 200;
  29137. var points = options.points;
  29138. var positions = new Array();
  29139. var indices = new Array();
  29140. var curvect = BABYLON.Vector3.Zero();
  29141. var lg = 0;
  29142. var nb = 0;
  29143. var shft = 0;
  29144. var dashshft = 0;
  29145. var curshft = 0;
  29146. var idx = 0;
  29147. var i = 0;
  29148. for (i = 0; i < points.length - 1; i++) {
  29149. points[i + 1].subtractToRef(points[i], curvect);
  29150. lg += curvect.length();
  29151. }
  29152. shft = lg / dashNb;
  29153. dashshft = dashSize * shft / (dashSize + gapSize);
  29154. for (i = 0; i < points.length - 1; i++) {
  29155. points[i + 1].subtractToRef(points[i], curvect);
  29156. nb = Math.floor(curvect.length() / shft);
  29157. curvect.normalize();
  29158. for (var j = 0; j < nb; j++) {
  29159. curshft = shft * j;
  29160. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29161. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29162. indices.push(idx, idx + 1);
  29163. idx += 2;
  29164. }
  29165. }
  29166. // Result
  29167. var vertexData = new VertexData();
  29168. vertexData.positions = positions;
  29169. vertexData.indices = indices;
  29170. return vertexData;
  29171. };
  29172. /**
  29173. * Creates the VertexData of the Ground.
  29174. */
  29175. VertexData.CreateGround = function (options) {
  29176. var indices = [];
  29177. var positions = [];
  29178. var normals = [];
  29179. var uvs = [];
  29180. var row, col;
  29181. var width = options.width || 1;
  29182. var height = options.height || 1;
  29183. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29184. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29185. for (row = 0; row <= subdivisionsY; row++) {
  29186. for (col = 0; col <= subdivisionsX; col++) {
  29187. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29188. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29189. positions.push(position.x, position.y, position.z);
  29190. normals.push(normal.x, normal.y, normal.z);
  29191. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29192. }
  29193. }
  29194. for (row = 0; row < subdivisionsY; row++) {
  29195. for (col = 0; col < subdivisionsX; col++) {
  29196. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29197. indices.push(col + 1 + row * (subdivisionsX + 1));
  29198. indices.push(col + row * (subdivisionsX + 1));
  29199. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29200. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29201. indices.push(col + row * (subdivisionsX + 1));
  29202. }
  29203. }
  29204. // Result
  29205. var vertexData = new VertexData();
  29206. vertexData.indices = indices;
  29207. vertexData.positions = positions;
  29208. vertexData.normals = normals;
  29209. vertexData.uvs = uvs;
  29210. return vertexData;
  29211. };
  29212. /**
  29213. * Creates the VertexData of the TiledGround.
  29214. */
  29215. VertexData.CreateTiledGround = function (options) {
  29216. var xmin = options.xmin || -1.0;
  29217. var zmin = options.zmin || -1.0;
  29218. var xmax = options.xmax || 1.0;
  29219. var zmax = options.zmax || 1.0;
  29220. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29221. var precision = options.precision || { w: 1, h: 1 };
  29222. var indices = new Array();
  29223. var positions = new Array();
  29224. var normals = new Array();
  29225. var uvs = new Array();
  29226. var row, col, tileRow, tileCol;
  29227. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29228. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29229. precision.w = (precision.w < 1) ? 1 : precision.w;
  29230. precision.h = (precision.h < 1) ? 1 : precision.h;
  29231. var tileSize = {
  29232. 'w': (xmax - xmin) / subdivisions.w,
  29233. 'h': (zmax - zmin) / subdivisions.h
  29234. };
  29235. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29236. // Indices
  29237. var base = positions.length / 3;
  29238. var rowLength = precision.w + 1;
  29239. for (row = 0; row < precision.h; row++) {
  29240. for (col = 0; col < precision.w; col++) {
  29241. var square = [
  29242. base + col + row * rowLength,
  29243. base + (col + 1) + row * rowLength,
  29244. base + (col + 1) + (row + 1) * rowLength,
  29245. base + col + (row + 1) * rowLength
  29246. ];
  29247. indices.push(square[1]);
  29248. indices.push(square[2]);
  29249. indices.push(square[3]);
  29250. indices.push(square[0]);
  29251. indices.push(square[1]);
  29252. indices.push(square[3]);
  29253. }
  29254. }
  29255. // Position, normals and uvs
  29256. var position = BABYLON.Vector3.Zero();
  29257. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29258. for (row = 0; row <= precision.h; row++) {
  29259. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29260. for (col = 0; col <= precision.w; col++) {
  29261. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29262. position.y = 0;
  29263. positions.push(position.x, position.y, position.z);
  29264. normals.push(normal.x, normal.y, normal.z);
  29265. uvs.push(col / precision.w, row / precision.h);
  29266. }
  29267. }
  29268. }
  29269. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29270. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29271. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29272. }
  29273. }
  29274. // Result
  29275. var vertexData = new VertexData();
  29276. vertexData.indices = indices;
  29277. vertexData.positions = positions;
  29278. vertexData.normals = normals;
  29279. vertexData.uvs = uvs;
  29280. return vertexData;
  29281. };
  29282. /**
  29283. * Creates the VertexData of the Ground designed from a heightmap.
  29284. */
  29285. VertexData.CreateGroundFromHeightMap = function (options) {
  29286. var indices = [];
  29287. var positions = [];
  29288. var normals = [];
  29289. var uvs = [];
  29290. var row, col;
  29291. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29292. // Vertices
  29293. for (row = 0; row <= options.subdivisions; row++) {
  29294. for (col = 0; col <= options.subdivisions; col++) {
  29295. 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));
  29296. // Compute height
  29297. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29298. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29299. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29300. var r = options.buffer[pos] / 255.0;
  29301. var g = options.buffer[pos + 1] / 255.0;
  29302. var b = options.buffer[pos + 2] / 255.0;
  29303. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29304. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29305. // Add vertex
  29306. positions.push(position.x, position.y, position.z);
  29307. normals.push(0, 0, 0);
  29308. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29309. }
  29310. }
  29311. // Indices
  29312. for (row = 0; row < options.subdivisions; row++) {
  29313. for (col = 0; col < options.subdivisions; col++) {
  29314. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29315. indices.push(col + 1 + row * (options.subdivisions + 1));
  29316. indices.push(col + row * (options.subdivisions + 1));
  29317. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29318. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29319. indices.push(col + row * (options.subdivisions + 1));
  29320. }
  29321. }
  29322. // Normals
  29323. VertexData.ComputeNormals(positions, indices, normals);
  29324. // Result
  29325. var vertexData = new VertexData();
  29326. vertexData.indices = indices;
  29327. vertexData.positions = positions;
  29328. vertexData.normals = normals;
  29329. vertexData.uvs = uvs;
  29330. return vertexData;
  29331. };
  29332. /**
  29333. * Creates the VertexData of the Plane.
  29334. */
  29335. VertexData.CreatePlane = function (options) {
  29336. var indices = [];
  29337. var positions = [];
  29338. var normals = [];
  29339. var uvs = [];
  29340. var width = options.width || options.size || 1;
  29341. var height = options.height || options.size || 1;
  29342. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29343. // Vertices
  29344. var halfWidth = width / 2.0;
  29345. var halfHeight = height / 2.0;
  29346. positions.push(-halfWidth, -halfHeight, 0);
  29347. normals.push(0, 0, -1.0);
  29348. uvs.push(0.0, 0.0);
  29349. positions.push(halfWidth, -halfHeight, 0);
  29350. normals.push(0, 0, -1.0);
  29351. uvs.push(1.0, 0.0);
  29352. positions.push(halfWidth, halfHeight, 0);
  29353. normals.push(0, 0, -1.0);
  29354. uvs.push(1.0, 1.0);
  29355. positions.push(-halfWidth, halfHeight, 0);
  29356. normals.push(0, 0, -1.0);
  29357. uvs.push(0.0, 1.0);
  29358. // Indices
  29359. indices.push(0);
  29360. indices.push(1);
  29361. indices.push(2);
  29362. indices.push(0);
  29363. indices.push(2);
  29364. indices.push(3);
  29365. // Sides
  29366. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29367. // Result
  29368. var vertexData = new VertexData();
  29369. vertexData.indices = indices;
  29370. vertexData.positions = positions;
  29371. vertexData.normals = normals;
  29372. vertexData.uvs = uvs;
  29373. return vertexData;
  29374. };
  29375. /**
  29376. * Creates the VertexData of the Disc or regular Polygon.
  29377. */
  29378. VertexData.CreateDisc = function (options) {
  29379. var positions = new Array();
  29380. var indices = new Array();
  29381. var normals = new Array();
  29382. var uvs = new Array();
  29383. var radius = options.radius || 0.5;
  29384. var tessellation = options.tessellation || 64;
  29385. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29386. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29387. // positions and uvs
  29388. positions.push(0, 0, 0); // disc center first
  29389. uvs.push(0.5, 0.5);
  29390. var theta = Math.PI * 2 * arc;
  29391. var step = theta / tessellation;
  29392. for (var a = 0; a < theta; a += step) {
  29393. var x = Math.cos(a);
  29394. var y = Math.sin(a);
  29395. var u = (x + 1) / 2;
  29396. var v = (1 - y) / 2;
  29397. positions.push(radius * x, radius * y, 0);
  29398. uvs.push(u, v);
  29399. }
  29400. if (arc === 1) {
  29401. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29402. uvs.push(uvs[2], uvs[3]);
  29403. }
  29404. //indices
  29405. var vertexNb = positions.length / 3;
  29406. for (var i = 1; i < vertexNb - 1; i++) {
  29407. indices.push(i + 1, 0, i);
  29408. }
  29409. // result
  29410. VertexData.ComputeNormals(positions, indices, normals);
  29411. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29412. var vertexData = new VertexData();
  29413. vertexData.indices = indices;
  29414. vertexData.positions = positions;
  29415. vertexData.normals = normals;
  29416. vertexData.uvs = uvs;
  29417. return vertexData;
  29418. };
  29419. /**
  29420. * Re-creates the VertexData of the Polygon for sideOrientation.
  29421. */
  29422. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29423. var faceUV = fUV || new Array(3);
  29424. var faceColors = fColors;
  29425. var colors = [];
  29426. // default face colors and UV if undefined
  29427. for (var f = 0; f < 3; f++) {
  29428. if (faceUV[f] === undefined) {
  29429. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29430. }
  29431. if (faceColors && faceColors[f] === undefined) {
  29432. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29433. }
  29434. }
  29435. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29436. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29437. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29438. var indices = polygon.getIndices();
  29439. // set face colours and textures
  29440. var idx = 0;
  29441. var face = 0;
  29442. for (var index = 0; index < normals.length; index += 3) {
  29443. //Edge Face no. 1
  29444. if (Math.abs(normals[index + 1]) < 0.001) {
  29445. face = 1;
  29446. }
  29447. //Top Face no. 0
  29448. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29449. face = 0;
  29450. }
  29451. //Bottom Face no. 2
  29452. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29453. face = 2;
  29454. }
  29455. idx = index / 3;
  29456. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29457. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29458. if (faceColors) {
  29459. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29460. }
  29461. }
  29462. // sides
  29463. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29464. // Result
  29465. var vertexData = new VertexData();
  29466. vertexData.indices = indices;
  29467. vertexData.positions = positions;
  29468. vertexData.normals = normals;
  29469. vertexData.uvs = uvs;
  29470. if (faceColors) {
  29471. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29472. vertexData.colors = totalColors;
  29473. }
  29474. return vertexData;
  29475. };
  29476. /**
  29477. * Creates the VertexData of the IcoSphere.
  29478. */
  29479. VertexData.CreateIcoSphere = function (options) {
  29480. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29481. var radius = options.radius || 1;
  29482. var flat = (options.flat === undefined) ? true : options.flat;
  29483. var subdivisions = options.subdivisions || 4;
  29484. var radiusX = options.radiusX || radius;
  29485. var radiusY = options.radiusY || radius;
  29486. var radiusZ = options.radiusZ || radius;
  29487. var t = (1 + Math.sqrt(5)) / 2;
  29488. // 12 vertex x,y,z
  29489. var ico_vertices = [
  29490. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29491. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29492. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29493. ];
  29494. // index of 3 vertex makes a face of icopshere
  29495. var ico_indices = [
  29496. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29497. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29498. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29499. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29500. ];
  29501. // vertex for uv have aliased position, not for UV
  29502. var vertices_unalias_id = [
  29503. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29504. // vertex alias
  29505. 0,
  29506. 2,
  29507. 3,
  29508. 3,
  29509. 3,
  29510. 4,
  29511. 7,
  29512. 8,
  29513. 9,
  29514. 9,
  29515. 10,
  29516. 11 // 23: B + 12
  29517. ];
  29518. // uv as integer step (not pixels !)
  29519. var ico_vertexuv = [
  29520. 5, 1, 3, 1, 6, 4, 0, 0,
  29521. 5, 3, 4, 2, 2, 2, 4, 0,
  29522. 2, 0, 1, 1, 6, 0, 6, 2,
  29523. // vertex alias (for same vertex on different faces)
  29524. 0, 4,
  29525. 3, 3,
  29526. 4, 4,
  29527. 3, 1,
  29528. 4, 2,
  29529. 4, 4,
  29530. 0, 2,
  29531. 1, 1,
  29532. 2, 2,
  29533. 3, 3,
  29534. 1, 3,
  29535. 2, 4 // 23: B + 12
  29536. ];
  29537. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29538. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29539. // First island of uv mapping
  29540. // v = 4h 3+ 2
  29541. // v = 3h 9+ 4
  29542. // v = 2h 9+ 5 B
  29543. // v = 1h 9 1 0
  29544. // v = 0h 3 8 7 A
  29545. // u = 0 1 2 3 4 5 6 *a
  29546. // Second island of uv mapping
  29547. // v = 4h 0+ B+ 4+
  29548. // v = 3h A+ 2+
  29549. // v = 2h 7+ 6 3+
  29550. // v = 1h 8+ 3+
  29551. // v = 0h
  29552. // u = 0 1 2 3 4 5 6 *a
  29553. // Face layout on texture UV mapping
  29554. // ============
  29555. // \ 4 /\ 16 / ======
  29556. // \ / \ / /\ 11 /
  29557. // \/ 7 \/ / \ /
  29558. // ======= / 10 \/
  29559. // /\ 17 /\ =======
  29560. // / \ / \ \ 15 /\
  29561. // / 8 \/ 12 \ \ / \
  29562. // ============ \/ 6 \
  29563. // \ 18 /\ ============
  29564. // \ / \ \ 5 /\ 0 /
  29565. // \/ 13 \ \ / \ /
  29566. // ======= \/ 1 \/
  29567. // =============
  29568. // /\ 19 /\ 2 /\
  29569. // / \ / \ / \
  29570. // / 14 \/ 9 \/ 3 \
  29571. // ===================
  29572. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29573. var ustep = 138 / 1024;
  29574. var vstep = 239 / 1024;
  29575. var uoffset = 60 / 1024;
  29576. var voffset = 26 / 1024;
  29577. // Second island should have margin, not to touch the first island
  29578. // avoid any borderline artefact in pixel rounding
  29579. var island_u_offset = -40 / 1024;
  29580. var island_v_offset = +20 / 1024;
  29581. // face is either island 0 or 1 :
  29582. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29583. var island = [
  29584. 0, 0, 0, 0, 1,
  29585. 0, 0, 1, 1, 0,
  29586. 0, 0, 1, 1, 0,
  29587. 0, 1, 1, 1, 0 // 15 - 19
  29588. ];
  29589. var indices = new Array();
  29590. var positions = new Array();
  29591. var normals = new Array();
  29592. var uvs = new Array();
  29593. var current_indice = 0;
  29594. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29595. var face_vertex_pos = new Array(3);
  29596. var face_vertex_uv = new Array(3);
  29597. var v012;
  29598. for (v012 = 0; v012 < 3; v012++) {
  29599. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29600. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29601. }
  29602. // create all with normals
  29603. for (var face = 0; face < 20; face++) {
  29604. // 3 vertex per face
  29605. for (v012 = 0; v012 < 3; v012++) {
  29606. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29607. var v_id = ico_indices[3 * face + v012];
  29608. // vertex have 3D position (x,y,z)
  29609. 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]);
  29610. // Normalize to get normal, then scale to radius
  29611. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29612. // uv Coordinates from vertex ID
  29613. 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);
  29614. }
  29615. // Subdivide the face (interpolate pos, norm, uv)
  29616. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29617. // - norm is linear interpolation of vertex corner normal
  29618. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29619. // - uv is linear interpolation
  29620. //
  29621. // Topology is as below for sub-divide by 2
  29622. // vertex shown as v0,v1,v2
  29623. // interp index is i1 to progress in range [v0,v1[
  29624. // interp index is i2 to progress in range [v0,v2[
  29625. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29626. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29627. //
  29628. //
  29629. // i2 v2
  29630. // ^ ^
  29631. // / / \
  29632. // / / \
  29633. // / / \
  29634. // / / (0,1) \
  29635. // / #---------\
  29636. // / / \ (0,0)'/ \
  29637. // / / \ / \
  29638. // / / \ / \
  29639. // / / (0,0) \ / (1,0) \
  29640. // / #---------#---------\
  29641. // v0 v1
  29642. //
  29643. // --------------------> i1
  29644. //
  29645. // interp of (i1,i2):
  29646. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29647. // along i1 : lerp(x0,x1, i1/(S-i2))
  29648. //
  29649. // centroid of triangle is needed to get help normal computation
  29650. // (c1,c2) are used for centroid location
  29651. var interp_vertex = function (i1, i2, c1, c2) {
  29652. // vertex is interpolated from
  29653. // - face_vertex_pos[0..2]
  29654. // - face_vertex_uv[0..2]
  29655. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29656. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29657. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29658. pos_interp.normalize();
  29659. var vertex_normal;
  29660. if (flat) {
  29661. // in flat mode, recalculate normal as face centroid normal
  29662. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29663. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29664. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29665. }
  29666. else {
  29667. // in smooth mode, recalculate normal from each single vertex position
  29668. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29669. }
  29670. // Vertex normal need correction due to X,Y,Z radius scaling
  29671. vertex_normal.x /= radiusX;
  29672. vertex_normal.y /= radiusY;
  29673. vertex_normal.z /= radiusZ;
  29674. vertex_normal.normalize();
  29675. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29676. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29677. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29678. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29679. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29680. uvs.push(uv_interp.x, uv_interp.y);
  29681. // push each vertex has member of a face
  29682. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29683. indices.push(current_indice);
  29684. current_indice++;
  29685. };
  29686. for (var i2 = 0; i2 < subdivisions; i2++) {
  29687. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29688. // face : (i1,i2) for /\ :
  29689. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29690. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29691. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29692. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29693. if (i1 + i2 + 1 < subdivisions) {
  29694. // face : (i1,i2)' for \/ :
  29695. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29696. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29697. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29698. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29699. }
  29700. }
  29701. }
  29702. }
  29703. // Sides
  29704. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29705. // Result
  29706. var vertexData = new VertexData();
  29707. vertexData.indices = indices;
  29708. vertexData.positions = positions;
  29709. vertexData.normals = normals;
  29710. vertexData.uvs = uvs;
  29711. return vertexData;
  29712. };
  29713. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29714. /**
  29715. * Creates the VertexData of the Polyhedron.
  29716. */
  29717. VertexData.CreatePolyhedron = function (options) {
  29718. // provided polyhedron types :
  29719. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29720. // 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)
  29721. var polyhedra = [];
  29722. 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]] };
  29723. 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]] };
  29724. polyhedra[2] = {
  29725. 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]],
  29726. 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]]
  29727. };
  29728. polyhedra[3] = {
  29729. 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]],
  29730. 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]]
  29731. };
  29732. polyhedra[4] = {
  29733. 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]],
  29734. 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]]
  29735. };
  29736. 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]] };
  29737. 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]] };
  29738. 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]] };
  29739. 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]] };
  29740. 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]] };
  29741. 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]] };
  29742. 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]] };
  29743. 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]] };
  29744. 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]] };
  29745. polyhedra[14] = {
  29746. 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]],
  29747. 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]]
  29748. };
  29749. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29750. var size = options.size;
  29751. var sizeX = options.sizeX || size || 1;
  29752. var sizeY = options.sizeY || size || 1;
  29753. var sizeZ = options.sizeZ || size || 1;
  29754. var data = options.custom || polyhedra[type];
  29755. var nbfaces = data.face.length;
  29756. var faceUV = options.faceUV || new Array(nbfaces);
  29757. var faceColors = options.faceColors;
  29758. var flat = (options.flat === undefined) ? true : options.flat;
  29759. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29760. var positions = new Array();
  29761. var indices = new Array();
  29762. var normals = new Array();
  29763. var uvs = new Array();
  29764. var colors = new Array();
  29765. var index = 0;
  29766. var faceIdx = 0; // face cursor in the array "indexes"
  29767. var indexes = new Array();
  29768. var i = 0;
  29769. var f = 0;
  29770. var u, v, ang, x, y, tmp;
  29771. // default face colors and UV if undefined
  29772. if (flat) {
  29773. for (f = 0; f < nbfaces; f++) {
  29774. if (faceColors && faceColors[f] === undefined) {
  29775. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29776. }
  29777. if (faceUV && faceUV[f] === undefined) {
  29778. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29779. }
  29780. }
  29781. }
  29782. if (!flat) {
  29783. for (i = 0; i < data.vertex.length; i++) {
  29784. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29785. uvs.push(0, 0);
  29786. }
  29787. for (f = 0; f < nbfaces; f++) {
  29788. for (i = 0; i < data.face[f].length - 2; i++) {
  29789. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29790. }
  29791. }
  29792. }
  29793. else {
  29794. for (f = 0; f < nbfaces; f++) {
  29795. var fl = data.face[f].length; // number of vertices of the current face
  29796. ang = 2 * Math.PI / fl;
  29797. x = 0.5 * Math.tan(ang / 2);
  29798. y = 0.5;
  29799. // positions, uvs, colors
  29800. for (i = 0; i < fl; i++) {
  29801. // positions
  29802. 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);
  29803. indexes.push(index);
  29804. index++;
  29805. // uvs
  29806. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29807. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29808. uvs.push(u, v);
  29809. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29810. y = x * Math.sin(ang) + y * Math.cos(ang);
  29811. x = tmp;
  29812. // colors
  29813. if (faceColors) {
  29814. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29815. }
  29816. }
  29817. // indices from indexes
  29818. for (i = 0; i < fl - 2; i++) {
  29819. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29820. }
  29821. faceIdx += fl;
  29822. }
  29823. }
  29824. VertexData.ComputeNormals(positions, indices, normals);
  29825. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29826. var vertexData = new VertexData();
  29827. vertexData.positions = positions;
  29828. vertexData.indices = indices;
  29829. vertexData.normals = normals;
  29830. vertexData.uvs = uvs;
  29831. if (faceColors && flat) {
  29832. vertexData.colors = colors;
  29833. }
  29834. return vertexData;
  29835. };
  29836. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29837. /**
  29838. * Creates the VertexData of the Torus Knot.
  29839. */
  29840. VertexData.CreateTorusKnot = function (options) {
  29841. var indices = new Array();
  29842. var positions = new Array();
  29843. var normals = new Array();
  29844. var uvs = new Array();
  29845. var radius = options.radius || 2;
  29846. var tube = options.tube || 0.5;
  29847. var radialSegments = options.radialSegments || 32;
  29848. var tubularSegments = options.tubularSegments || 32;
  29849. var p = options.p || 2;
  29850. var q = options.q || 3;
  29851. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29852. // Helper
  29853. var getPos = function (angle) {
  29854. var cu = Math.cos(angle);
  29855. var su = Math.sin(angle);
  29856. var quOverP = q / p * angle;
  29857. var cs = Math.cos(quOverP);
  29858. var tx = radius * (2 + cs) * 0.5 * cu;
  29859. var ty = radius * (2 + cs) * su * 0.5;
  29860. var tz = radius * Math.sin(quOverP) * 0.5;
  29861. return new BABYLON.Vector3(tx, ty, tz);
  29862. };
  29863. // Vertices
  29864. var i;
  29865. var j;
  29866. for (i = 0; i <= radialSegments; i++) {
  29867. var modI = i % radialSegments;
  29868. var u = modI / radialSegments * 2 * p * Math.PI;
  29869. var p1 = getPos(u);
  29870. var p2 = getPos(u + 0.01);
  29871. var tang = p2.subtract(p1);
  29872. var n = p2.add(p1);
  29873. var bitan = BABYLON.Vector3.Cross(tang, n);
  29874. n = BABYLON.Vector3.Cross(bitan, tang);
  29875. bitan.normalize();
  29876. n.normalize();
  29877. for (j = 0; j < tubularSegments; j++) {
  29878. var modJ = j % tubularSegments;
  29879. var v = modJ / tubularSegments * 2 * Math.PI;
  29880. var cx = -tube * Math.cos(v);
  29881. var cy = tube * Math.sin(v);
  29882. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29883. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29884. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29885. uvs.push(i / radialSegments);
  29886. uvs.push(j / tubularSegments);
  29887. }
  29888. }
  29889. for (i = 0; i < radialSegments; i++) {
  29890. for (j = 0; j < tubularSegments; j++) {
  29891. var jNext = (j + 1) % tubularSegments;
  29892. var a = i * tubularSegments + j;
  29893. var b = (i + 1) * tubularSegments + j;
  29894. var c = (i + 1) * tubularSegments + jNext;
  29895. var d = i * tubularSegments + jNext;
  29896. indices.push(d);
  29897. indices.push(b);
  29898. indices.push(a);
  29899. indices.push(d);
  29900. indices.push(c);
  29901. indices.push(b);
  29902. }
  29903. }
  29904. // Normals
  29905. VertexData.ComputeNormals(positions, indices, normals);
  29906. // Sides
  29907. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29908. // Result
  29909. var vertexData = new VertexData();
  29910. vertexData.indices = indices;
  29911. vertexData.positions = positions;
  29912. vertexData.normals = normals;
  29913. vertexData.uvs = uvs;
  29914. return vertexData;
  29915. };
  29916. // Tools
  29917. /**
  29918. * @param {any} - positions (number[] or Float32Array)
  29919. * @param {any} - indices (number[] or Uint16Array)
  29920. * @param {any} - normals (number[] or Float32Array)
  29921. * options (optional) :
  29922. * facetPositions : optional array of facet positions (vector3)
  29923. * facetNormals : optional array of facet normals (vector3)
  29924. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  29925. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  29926. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  29927. * bbSize : optional bounding box size data, required for facetPartitioning computation
  29928. * bInfo : optional bounding info, required for facetPartitioning computation
  29929. */
  29930. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  29931. // temporary scalar variables
  29932. var index = 0; // facet index
  29933. var p1p2x = 0.0; // p1p2 vector x coordinate
  29934. var p1p2y = 0.0; // p1p2 vector y coordinate
  29935. var p1p2z = 0.0; // p1p2 vector z coordinate
  29936. var p3p2x = 0.0; // p3p2 vector x coordinate
  29937. var p3p2y = 0.0; // p3p2 vector y coordinate
  29938. var p3p2z = 0.0; // p3p2 vector z coordinate
  29939. var faceNormalx = 0.0; // facet normal x coordinate
  29940. var faceNormaly = 0.0; // facet normal y coordinate
  29941. var faceNormalz = 0.0; // facet normal z coordinate
  29942. var length = 0.0; // facet normal length before normalization
  29943. var v1x = 0; // vector1 x index in the positions array
  29944. var v1y = 0; // vector1 y index in the positions array
  29945. var v1z = 0; // vector1 z index in the positions array
  29946. var v2x = 0; // vector2 x index in the positions array
  29947. var v2y = 0; // vector2 y index in the positions array
  29948. var v2z = 0; // vector2 z index in the positions array
  29949. var v3x = 0; // vector3 x index in the positions array
  29950. var v3y = 0; // vector3 y index in the positions array
  29951. var v3z = 0; // vector3 z index in the positions array
  29952. var computeFacetNormals = false;
  29953. var computeFacetPositions = false;
  29954. var computeFacetPartitioning = false;
  29955. var faceNormalSign = 1;
  29956. var ratio = 0;
  29957. if (options) {
  29958. computeFacetNormals = (options.facetNormals) ? true : false;
  29959. computeFacetPositions = (options.facetPositions) ? true : false;
  29960. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  29961. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  29962. ratio = options.ratio || 0;
  29963. }
  29964. // facetPartitioning reinit if needed
  29965. var xSubRatio = 0;
  29966. var ySubRatio = 0;
  29967. var zSubRatio = 0;
  29968. var subSq = 0;
  29969. if (computeFacetPartitioning && options && options.bbSize) {
  29970. var ox = 0; // X partitioning index for facet position
  29971. var oy = 0; // Y partinioning index for facet position
  29972. var oz = 0; // Z partinioning index for facet position
  29973. var b1x = 0; // X partitioning index for facet v1 vertex
  29974. var b1y = 0; // Y partitioning index for facet v1 vertex
  29975. var b1z = 0; // z partitioning index for facet v1 vertex
  29976. var b2x = 0; // X partitioning index for facet v2 vertex
  29977. var b2y = 0; // Y partitioning index for facet v2 vertex
  29978. var b2z = 0; // Z partitioning index for facet v2 vertex
  29979. var b3x = 0; // X partitioning index for facet v3 vertex
  29980. var b3y = 0; // Y partitioning index for facet v3 vertex
  29981. var b3z = 0; // Z partitioning index for facet v3 vertex
  29982. var block_idx_o = 0; // facet barycenter block index
  29983. var block_idx_v1 = 0; // v1 vertex block index
  29984. var block_idx_v2 = 0; // v2 vertex block index
  29985. var block_idx_v3 = 0; // v3 vertex block index
  29986. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  29987. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  29988. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  29989. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  29990. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  29991. subSq = options.subDiv.max * options.subDiv.max;
  29992. options.facetPartitioning.length = 0;
  29993. }
  29994. // reset the normals
  29995. for (index = 0; index < positions.length; index++) {
  29996. normals[index] = 0.0;
  29997. }
  29998. // Loop : 1 indice triplet = 1 facet
  29999. var nbFaces = indices.length / 3;
  30000. for (index = 0; index < nbFaces; index++) {
  30001. // get the indexes of the coordinates of each vertex of the facet
  30002. v1x = indices[index * 3] * 3;
  30003. v1y = v1x + 1;
  30004. v1z = v1x + 2;
  30005. v2x = indices[index * 3 + 1] * 3;
  30006. v2y = v2x + 1;
  30007. v2z = v2x + 2;
  30008. v3x = indices[index * 3 + 2] * 3;
  30009. v3y = v3x + 1;
  30010. v3z = v3x + 2;
  30011. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30012. p1p2y = positions[v1y] - positions[v2y];
  30013. p1p2z = positions[v1z] - positions[v2z];
  30014. p3p2x = positions[v3x] - positions[v2x];
  30015. p3p2y = positions[v3y] - positions[v2y];
  30016. p3p2z = positions[v3z] - positions[v2z];
  30017. // compute the face normal with the cross product
  30018. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30019. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30020. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30021. // normalize this normal and store it in the array facetData
  30022. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30023. length = (length === 0) ? 1.0 : length;
  30024. faceNormalx /= length;
  30025. faceNormaly /= length;
  30026. faceNormalz /= length;
  30027. if (computeFacetNormals && options) {
  30028. options.facetNormals[index].x = faceNormalx;
  30029. options.facetNormals[index].y = faceNormaly;
  30030. options.facetNormals[index].z = faceNormalz;
  30031. }
  30032. if (computeFacetPositions && options) {
  30033. // compute and the facet barycenter coordinates in the array facetPositions
  30034. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30035. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30036. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30037. }
  30038. if (computeFacetPartitioning && options) {
  30039. // store the facet indexes in arrays in the main facetPartitioning array :
  30040. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30041. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30042. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30043. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30044. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30045. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30046. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30047. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30048. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30049. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30050. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30051. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30052. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30053. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30054. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30055. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30056. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30057. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30058. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30059. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30060. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30061. // push each facet index in each block containing the vertex
  30062. options.facetPartitioning[block_idx_v1].push(index);
  30063. if (block_idx_v2 != block_idx_v1) {
  30064. options.facetPartitioning[block_idx_v2].push(index);
  30065. }
  30066. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30067. options.facetPartitioning[block_idx_v3].push(index);
  30068. }
  30069. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30070. options.facetPartitioning[block_idx_o].push(index);
  30071. }
  30072. }
  30073. // compute the normals anyway
  30074. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30075. normals[v1y] += faceNormaly;
  30076. normals[v1z] += faceNormalz;
  30077. normals[v2x] += faceNormalx;
  30078. normals[v2y] += faceNormaly;
  30079. normals[v2z] += faceNormalz;
  30080. normals[v3x] += faceNormalx;
  30081. normals[v3y] += faceNormaly;
  30082. normals[v3z] += faceNormalz;
  30083. }
  30084. // last normalization of each normal
  30085. for (index = 0; index < normals.length / 3; index++) {
  30086. faceNormalx = normals[index * 3];
  30087. faceNormaly = normals[index * 3 + 1];
  30088. faceNormalz = normals[index * 3 + 2];
  30089. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30090. length = (length === 0) ? 1.0 : length;
  30091. faceNormalx /= length;
  30092. faceNormaly /= length;
  30093. faceNormalz /= length;
  30094. normals[index * 3] = faceNormalx;
  30095. normals[index * 3 + 1] = faceNormaly;
  30096. normals[index * 3 + 2] = faceNormalz;
  30097. }
  30098. };
  30099. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30100. var li = indices.length;
  30101. var ln = normals.length;
  30102. var i;
  30103. var n;
  30104. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30105. switch (sideOrientation) {
  30106. case BABYLON.Mesh.FRONTSIDE:
  30107. // nothing changed
  30108. break;
  30109. case BABYLON.Mesh.BACKSIDE:
  30110. var tmp;
  30111. // indices
  30112. for (i = 0; i < li; i += 3) {
  30113. tmp = indices[i];
  30114. indices[i] = indices[i + 2];
  30115. indices[i + 2] = tmp;
  30116. }
  30117. // normals
  30118. for (n = 0; n < ln; n++) {
  30119. normals[n] = -normals[n];
  30120. }
  30121. break;
  30122. case BABYLON.Mesh.DOUBLESIDE:
  30123. // positions
  30124. var lp = positions.length;
  30125. var l = lp / 3;
  30126. for (var p = 0; p < lp; p++) {
  30127. positions[lp + p] = positions[p];
  30128. }
  30129. // indices
  30130. for (i = 0; i < li; i += 3) {
  30131. indices[i + li] = indices[i + 2] + l;
  30132. indices[i + 1 + li] = indices[i + 1] + l;
  30133. indices[i + 2 + li] = indices[i] + l;
  30134. }
  30135. // normals
  30136. for (n = 0; n < ln; n++) {
  30137. normals[ln + n] = -normals[n];
  30138. }
  30139. // uvs
  30140. var lu = uvs.length;
  30141. var u = 0;
  30142. for (u = 0; u < lu; u++) {
  30143. uvs[u + lu] = uvs[u];
  30144. }
  30145. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30146. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30147. u = 0;
  30148. for (i = 0; i < lu / 2; i++) {
  30149. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30150. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30151. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30152. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30153. u += 2;
  30154. }
  30155. break;
  30156. }
  30157. };
  30158. /**
  30159. * Creates a new VertexData from the imported parameters.
  30160. */
  30161. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30162. var vertexData = new VertexData();
  30163. // positions
  30164. var positions = parsedVertexData.positions;
  30165. if (positions) {
  30166. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30167. }
  30168. // normals
  30169. var normals = parsedVertexData.normals;
  30170. if (normals) {
  30171. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30172. }
  30173. // tangents
  30174. var tangents = parsedVertexData.tangents;
  30175. if (tangents) {
  30176. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30177. }
  30178. // uvs
  30179. var uvs = parsedVertexData.uvs;
  30180. if (uvs) {
  30181. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30182. }
  30183. // uv2s
  30184. var uv2s = parsedVertexData.uv2s;
  30185. if (uv2s) {
  30186. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30187. }
  30188. // uv3s
  30189. var uv3s = parsedVertexData.uv3s;
  30190. if (uv3s) {
  30191. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30192. }
  30193. // uv4s
  30194. var uv4s = parsedVertexData.uv4s;
  30195. if (uv4s) {
  30196. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30197. }
  30198. // uv5s
  30199. var uv5s = parsedVertexData.uv5s;
  30200. if (uv5s) {
  30201. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30202. }
  30203. // uv6s
  30204. var uv6s = parsedVertexData.uv6s;
  30205. if (uv6s) {
  30206. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30207. }
  30208. // colors
  30209. var colors = parsedVertexData.colors;
  30210. if (colors) {
  30211. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30212. }
  30213. // matricesIndices
  30214. var matricesIndices = parsedVertexData.matricesIndices;
  30215. if (matricesIndices) {
  30216. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30217. }
  30218. // matricesWeights
  30219. var matricesWeights = parsedVertexData.matricesWeights;
  30220. if (matricesWeights) {
  30221. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30222. }
  30223. // indices
  30224. var indices = parsedVertexData.indices;
  30225. if (indices) {
  30226. vertexData.indices = indices;
  30227. }
  30228. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30229. };
  30230. return VertexData;
  30231. }());
  30232. BABYLON.VertexData = VertexData;
  30233. })(BABYLON || (BABYLON = {}));
  30234. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30235. var BABYLON;
  30236. (function (BABYLON) {
  30237. var Geometry = /** @class */ (function () {
  30238. function Geometry(id, scene, vertexData, updatable, mesh) {
  30239. if (updatable === void 0) { updatable = false; }
  30240. if (mesh === void 0) { mesh = null; }
  30241. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30242. this._totalVertices = 0;
  30243. this._isDisposed = false;
  30244. this._indexBufferIsUpdatable = false;
  30245. this.id = id;
  30246. this._engine = scene.getEngine();
  30247. this._meshes = [];
  30248. this._scene = scene;
  30249. //Init vertex buffer cache
  30250. this._vertexBuffers = {};
  30251. this._indices = [];
  30252. this._updatable = updatable;
  30253. // vertexData
  30254. if (vertexData) {
  30255. this.setAllVerticesData(vertexData, updatable);
  30256. }
  30257. else {
  30258. this._totalVertices = 0;
  30259. this._indices = [];
  30260. }
  30261. if (this._engine.getCaps().vertexArrayObject) {
  30262. this._vertexArrayObjects = {};
  30263. }
  30264. // applyToMesh
  30265. if (mesh) {
  30266. if (mesh.getClassName() === "LinesMesh") {
  30267. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30268. this.updateExtend();
  30269. }
  30270. this.applyToMesh(mesh);
  30271. mesh.computeWorldMatrix(true);
  30272. }
  30273. }
  30274. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30275. /**
  30276. * 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
  30277. * @returns The Bias Vector
  30278. */
  30279. get: function () {
  30280. return this._boundingBias;
  30281. },
  30282. set: function (value) {
  30283. if (this._boundingBias && this._boundingBias.equals(value)) {
  30284. return;
  30285. }
  30286. this._boundingBias = value.clone();
  30287. this.updateBoundingInfo(true, null);
  30288. },
  30289. enumerable: true,
  30290. configurable: true
  30291. });
  30292. Geometry.CreateGeometryForMesh = function (mesh) {
  30293. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30294. geometry.applyToMesh(mesh);
  30295. return geometry;
  30296. };
  30297. Object.defineProperty(Geometry.prototype, "extend", {
  30298. get: function () {
  30299. return this._extend;
  30300. },
  30301. enumerable: true,
  30302. configurable: true
  30303. });
  30304. Geometry.prototype.getScene = function () {
  30305. return this._scene;
  30306. };
  30307. Geometry.prototype.getEngine = function () {
  30308. return this._engine;
  30309. };
  30310. Geometry.prototype.isReady = function () {
  30311. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30312. };
  30313. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30314. get: function () {
  30315. for (var index = 0; index < this._meshes.length; index++) {
  30316. if (!this._meshes[index].doNotSerialize) {
  30317. return false;
  30318. }
  30319. }
  30320. return true;
  30321. },
  30322. enumerable: true,
  30323. configurable: true
  30324. });
  30325. Geometry.prototype._rebuild = function () {
  30326. if (this._vertexArrayObjects) {
  30327. this._vertexArrayObjects = {};
  30328. }
  30329. // Index buffer
  30330. if (this._meshes.length !== 0 && this._indices) {
  30331. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30332. }
  30333. // Vertex buffers
  30334. for (var key in this._vertexBuffers) {
  30335. var vertexBuffer = this._vertexBuffers[key];
  30336. vertexBuffer._rebuild();
  30337. }
  30338. };
  30339. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30340. vertexData.applyToGeometry(this, updatable);
  30341. this.notifyUpdate();
  30342. };
  30343. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30344. if (updatable === void 0) { updatable = false; }
  30345. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30346. this.setVerticesBuffer(buffer);
  30347. };
  30348. Geometry.prototype.removeVerticesData = function (kind) {
  30349. if (this._vertexBuffers[kind]) {
  30350. this._vertexBuffers[kind].dispose();
  30351. delete this._vertexBuffers[kind];
  30352. }
  30353. };
  30354. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30355. var kind = buffer.getKind();
  30356. if (this._vertexBuffers[kind]) {
  30357. this._vertexBuffers[kind].dispose();
  30358. }
  30359. this._vertexBuffers[kind] = buffer;
  30360. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30361. var data = buffer.getData();
  30362. var stride = buffer.getStrideSize();
  30363. this._totalVertices = data.length / stride;
  30364. this.updateExtend(data, stride);
  30365. this._resetPointsArrayCache();
  30366. var meshes = this._meshes;
  30367. var numOfMeshes = meshes.length;
  30368. for (var index = 0; index < numOfMeshes; index++) {
  30369. var mesh = meshes[index];
  30370. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30371. mesh._createGlobalSubMesh(false);
  30372. mesh.computeWorldMatrix(true);
  30373. }
  30374. }
  30375. this.notifyUpdate(kind);
  30376. if (this._vertexArrayObjects) {
  30377. this._disposeVertexArrayObjects();
  30378. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30379. }
  30380. };
  30381. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30382. var vertexBuffer = this.getVertexBuffer(kind);
  30383. if (!vertexBuffer) {
  30384. return;
  30385. }
  30386. vertexBuffer.updateDirectly(data, offset);
  30387. this.notifyUpdate(kind);
  30388. };
  30389. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30390. if (updateExtends === void 0) { updateExtends = false; }
  30391. var vertexBuffer = this.getVertexBuffer(kind);
  30392. if (!vertexBuffer) {
  30393. return;
  30394. }
  30395. vertexBuffer.update(data);
  30396. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30397. var stride = vertexBuffer.getStrideSize();
  30398. this._totalVertices = data.length / stride;
  30399. this.updateBoundingInfo(updateExtends, data);
  30400. }
  30401. this.notifyUpdate(kind);
  30402. };
  30403. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30404. if (updateExtends) {
  30405. this.updateExtend(data);
  30406. }
  30407. var meshes = this._meshes;
  30408. var numOfMeshes = meshes.length;
  30409. this._resetPointsArrayCache();
  30410. for (var index = 0; index < numOfMeshes; index++) {
  30411. var mesh = meshes[index];
  30412. if (updateExtends) {
  30413. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30414. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30415. var subMesh = mesh.subMeshes[subIndex];
  30416. subMesh.refreshBoundingInfo();
  30417. }
  30418. }
  30419. }
  30420. };
  30421. Geometry.prototype._bind = function (effect, indexToBind) {
  30422. if (!effect) {
  30423. return;
  30424. }
  30425. if (indexToBind === undefined) {
  30426. indexToBind = this._indexBuffer;
  30427. }
  30428. var vbs = this.getVertexBuffers();
  30429. if (!vbs) {
  30430. return;
  30431. }
  30432. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30433. this._engine.bindBuffers(vbs, indexToBind, effect);
  30434. return;
  30435. }
  30436. // Using VAO
  30437. if (!this._vertexArrayObjects[effect.key]) {
  30438. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30439. }
  30440. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30441. };
  30442. Geometry.prototype.getTotalVertices = function () {
  30443. if (!this.isReady()) {
  30444. return 0;
  30445. }
  30446. return this._totalVertices;
  30447. };
  30448. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30449. var vertexBuffer = this.getVertexBuffer(kind);
  30450. if (!vertexBuffer) {
  30451. return null;
  30452. }
  30453. var orig = vertexBuffer.getData();
  30454. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  30455. return orig;
  30456. }
  30457. else {
  30458. var len = orig.length;
  30459. var copy = [];
  30460. for (var i = 0; i < len; i++) {
  30461. copy.push(orig[i]);
  30462. }
  30463. return copy;
  30464. }
  30465. };
  30466. /**
  30467. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30468. * Possible `kind` values :
  30469. * - BABYLON.VertexBuffer.PositionKind
  30470. * - BABYLON.VertexBuffer.UVKind
  30471. * - BABYLON.VertexBuffer.UV2Kind
  30472. * - BABYLON.VertexBuffer.UV3Kind
  30473. * - BABYLON.VertexBuffer.UV4Kind
  30474. * - BABYLON.VertexBuffer.UV5Kind
  30475. * - BABYLON.VertexBuffer.UV6Kind
  30476. * - BABYLON.VertexBuffer.ColorKind
  30477. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30478. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30479. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30480. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30481. */
  30482. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  30483. var vb = this._vertexBuffers[kind];
  30484. if (!vb) {
  30485. return false;
  30486. }
  30487. return vb.isUpdatable();
  30488. };
  30489. Geometry.prototype.getVertexBuffer = function (kind) {
  30490. if (!this.isReady()) {
  30491. return null;
  30492. }
  30493. return this._vertexBuffers[kind];
  30494. };
  30495. Geometry.prototype.getVertexBuffers = function () {
  30496. if (!this.isReady()) {
  30497. return null;
  30498. }
  30499. return this._vertexBuffers;
  30500. };
  30501. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30502. if (!this._vertexBuffers) {
  30503. if (this._delayInfo) {
  30504. return this._delayInfo.indexOf(kind) !== -1;
  30505. }
  30506. return false;
  30507. }
  30508. return this._vertexBuffers[kind] !== undefined;
  30509. };
  30510. Geometry.prototype.getVerticesDataKinds = function () {
  30511. var result = [];
  30512. var kind;
  30513. if (!this._vertexBuffers && this._delayInfo) {
  30514. for (kind in this._delayInfo) {
  30515. result.push(kind);
  30516. }
  30517. }
  30518. else {
  30519. for (kind in this._vertexBuffers) {
  30520. result.push(kind);
  30521. }
  30522. }
  30523. return result;
  30524. };
  30525. Geometry.prototype.updateIndices = function (indices, offset) {
  30526. if (!this._indexBuffer) {
  30527. return;
  30528. }
  30529. if (!this._indexBufferIsUpdatable) {
  30530. this.setIndices(indices, null, true);
  30531. }
  30532. else {
  30533. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  30534. }
  30535. };
  30536. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  30537. if (totalVertices === void 0) { totalVertices = null; }
  30538. if (updatable === void 0) { updatable = false; }
  30539. if (this._indexBuffer) {
  30540. this._engine._releaseBuffer(this._indexBuffer);
  30541. }
  30542. this._disposeVertexArrayObjects();
  30543. this._indices = indices;
  30544. this._indexBufferIsUpdatable = updatable;
  30545. if (this._meshes.length !== 0 && this._indices) {
  30546. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  30547. }
  30548. if (totalVertices != undefined) {
  30549. this._totalVertices = totalVertices;
  30550. }
  30551. var meshes = this._meshes;
  30552. var numOfMeshes = meshes.length;
  30553. for (var index = 0; index < numOfMeshes; index++) {
  30554. meshes[index]._createGlobalSubMesh(true);
  30555. }
  30556. this.notifyUpdate();
  30557. };
  30558. Geometry.prototype.getTotalIndices = function () {
  30559. if (!this.isReady()) {
  30560. return 0;
  30561. }
  30562. return this._indices.length;
  30563. };
  30564. Geometry.prototype.getIndices = function (copyWhenShared) {
  30565. if (!this.isReady()) {
  30566. return null;
  30567. }
  30568. var orig = this._indices;
  30569. if (!copyWhenShared || this._meshes.length === 1) {
  30570. return orig;
  30571. }
  30572. else {
  30573. var len = orig.length;
  30574. var copy = [];
  30575. for (var i = 0; i < len; i++) {
  30576. copy.push(orig[i]);
  30577. }
  30578. return copy;
  30579. }
  30580. };
  30581. Geometry.prototype.getIndexBuffer = function () {
  30582. if (!this.isReady()) {
  30583. return null;
  30584. }
  30585. return this._indexBuffer;
  30586. };
  30587. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  30588. if (effect === void 0) { effect = null; }
  30589. if (!effect || !this._vertexArrayObjects) {
  30590. return;
  30591. }
  30592. if (this._vertexArrayObjects[effect.key]) {
  30593. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  30594. delete this._vertexArrayObjects[effect.key];
  30595. }
  30596. };
  30597. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30598. var meshes = this._meshes;
  30599. var index = meshes.indexOf(mesh);
  30600. if (index === -1) {
  30601. return;
  30602. }
  30603. meshes.splice(index, 1);
  30604. mesh._geometry = null;
  30605. if (meshes.length === 0 && shouldDispose) {
  30606. this.dispose();
  30607. }
  30608. };
  30609. Geometry.prototype.applyToMesh = function (mesh) {
  30610. if (mesh._geometry === this) {
  30611. return;
  30612. }
  30613. var previousGeometry = mesh._geometry;
  30614. if (previousGeometry) {
  30615. previousGeometry.releaseForMesh(mesh);
  30616. }
  30617. var meshes = this._meshes;
  30618. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30619. mesh._geometry = this;
  30620. this._scene.pushGeometry(this);
  30621. meshes.push(mesh);
  30622. if (this.isReady()) {
  30623. this._applyToMesh(mesh);
  30624. }
  30625. else {
  30626. mesh._boundingInfo = this._boundingInfo;
  30627. }
  30628. };
  30629. Geometry.prototype.updateExtend = function (data, stride) {
  30630. if (data === void 0) { data = null; }
  30631. if (!data) {
  30632. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  30633. }
  30634. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  30635. };
  30636. Geometry.prototype._applyToMesh = function (mesh) {
  30637. var numOfMeshes = this._meshes.length;
  30638. // vertexBuffers
  30639. for (var kind in this._vertexBuffers) {
  30640. if (numOfMeshes === 1) {
  30641. this._vertexBuffers[kind].create();
  30642. }
  30643. var buffer = this._vertexBuffers[kind].getBuffer();
  30644. if (buffer)
  30645. buffer.references = numOfMeshes;
  30646. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30647. if (!this._extend) {
  30648. this.updateExtend(this._vertexBuffers[kind].getData());
  30649. }
  30650. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30651. mesh._createGlobalSubMesh(false);
  30652. //bounding info was just created again, world matrix should be applied again.
  30653. mesh._updateBoundingInfo();
  30654. }
  30655. }
  30656. // indexBuffer
  30657. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  30658. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30659. }
  30660. if (this._indexBuffer) {
  30661. this._indexBuffer.references = numOfMeshes;
  30662. }
  30663. };
  30664. Geometry.prototype.notifyUpdate = function (kind) {
  30665. if (this.onGeometryUpdated) {
  30666. this.onGeometryUpdated(this, kind);
  30667. }
  30668. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  30669. var mesh = _a[_i];
  30670. mesh._markSubMeshesAsAttributesDirty();
  30671. }
  30672. };
  30673. Geometry.prototype.load = function (scene, onLoaded) {
  30674. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30675. return;
  30676. }
  30677. if (this.isReady()) {
  30678. if (onLoaded) {
  30679. onLoaded();
  30680. }
  30681. return;
  30682. }
  30683. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30684. this._queueLoad(scene, onLoaded);
  30685. };
  30686. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  30687. var _this = this;
  30688. if (!this.delayLoadingFile) {
  30689. return;
  30690. }
  30691. scene._addPendingData(this);
  30692. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30693. if (!_this._delayLoadingFunction) {
  30694. return;
  30695. }
  30696. _this._delayLoadingFunction(JSON.parse(data), _this);
  30697. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30698. _this._delayInfo = [];
  30699. scene._removePendingData(_this);
  30700. var meshes = _this._meshes;
  30701. var numOfMeshes = meshes.length;
  30702. for (var index = 0; index < numOfMeshes; index++) {
  30703. _this._applyToMesh(meshes[index]);
  30704. }
  30705. if (onLoaded) {
  30706. onLoaded();
  30707. }
  30708. }, function () { }, scene.database);
  30709. };
  30710. /**
  30711. * Invert the geometry to move from a right handed system to a left handed one.
  30712. */
  30713. Geometry.prototype.toLeftHanded = function () {
  30714. // Flip faces
  30715. var tIndices = this.getIndices(false);
  30716. if (tIndices != null && tIndices.length > 0) {
  30717. for (var i = 0; i < tIndices.length; i += 3) {
  30718. var tTemp = tIndices[i + 0];
  30719. tIndices[i + 0] = tIndices[i + 2];
  30720. tIndices[i + 2] = tTemp;
  30721. }
  30722. this.setIndices(tIndices);
  30723. }
  30724. // Negate position.z
  30725. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  30726. if (tPositions != null && tPositions.length > 0) {
  30727. for (var i = 0; i < tPositions.length; i += 3) {
  30728. tPositions[i + 2] = -tPositions[i + 2];
  30729. }
  30730. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  30731. }
  30732. // Negate normal.z
  30733. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  30734. if (tNormals != null && tNormals.length > 0) {
  30735. for (var i = 0; i < tNormals.length; i += 3) {
  30736. tNormals[i + 2] = -tNormals[i + 2];
  30737. }
  30738. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  30739. }
  30740. };
  30741. // Cache
  30742. Geometry.prototype._resetPointsArrayCache = function () {
  30743. this._positions = null;
  30744. };
  30745. Geometry.prototype._generatePointsArray = function () {
  30746. if (this._positions)
  30747. return true;
  30748. this._positions = [];
  30749. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30750. if (!data) {
  30751. return false;
  30752. }
  30753. for (var index = 0; index < data.length; index += 3) {
  30754. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  30755. }
  30756. return true;
  30757. };
  30758. Geometry.prototype.isDisposed = function () {
  30759. return this._isDisposed;
  30760. };
  30761. Geometry.prototype._disposeVertexArrayObjects = function () {
  30762. if (this._vertexArrayObjects) {
  30763. for (var kind in this._vertexArrayObjects) {
  30764. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  30765. }
  30766. this._vertexArrayObjects = {};
  30767. }
  30768. };
  30769. Geometry.prototype.dispose = function () {
  30770. var meshes = this._meshes;
  30771. var numOfMeshes = meshes.length;
  30772. var index;
  30773. for (index = 0; index < numOfMeshes; index++) {
  30774. this.releaseForMesh(meshes[index]);
  30775. }
  30776. this._meshes = [];
  30777. this._disposeVertexArrayObjects();
  30778. for (var kind in this._vertexBuffers) {
  30779. this._vertexBuffers[kind].dispose();
  30780. }
  30781. this._vertexBuffers = {};
  30782. this._totalVertices = 0;
  30783. if (this._indexBuffer) {
  30784. this._engine._releaseBuffer(this._indexBuffer);
  30785. }
  30786. this._indexBuffer = null;
  30787. this._indices = [];
  30788. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30789. this.delayLoadingFile = null;
  30790. this._delayLoadingFunction = null;
  30791. this._delayInfo = [];
  30792. this._boundingInfo = null;
  30793. this._scene.removeGeometry(this);
  30794. this._isDisposed = true;
  30795. };
  30796. Geometry.prototype.copy = function (id) {
  30797. var vertexData = new BABYLON.VertexData();
  30798. vertexData.indices = [];
  30799. var indices = this.getIndices();
  30800. if (indices) {
  30801. for (var index = 0; index < indices.length; index++) {
  30802. vertexData.indices.push(indices[index]);
  30803. }
  30804. }
  30805. var updatable = false;
  30806. var stopChecking = false;
  30807. var kind;
  30808. for (kind in this._vertexBuffers) {
  30809. // using slice() to make a copy of the array and not just reference it
  30810. var data = this.getVerticesData(kind);
  30811. if (data instanceof Float32Array) {
  30812. vertexData.set(new Float32Array(data), kind);
  30813. }
  30814. else {
  30815. vertexData.set(data.slice(0), kind);
  30816. }
  30817. if (!stopChecking) {
  30818. var vb = this.getVertexBuffer(kind);
  30819. if (vb) {
  30820. updatable = vb.isUpdatable();
  30821. stopChecking = !updatable;
  30822. }
  30823. }
  30824. }
  30825. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  30826. geometry.delayLoadState = this.delayLoadState;
  30827. geometry.delayLoadingFile = this.delayLoadingFile;
  30828. geometry._delayLoadingFunction = this._delayLoadingFunction;
  30829. for (kind in this._delayInfo) {
  30830. geometry._delayInfo = geometry._delayInfo || [];
  30831. geometry._delayInfo.push(kind);
  30832. }
  30833. // Bounding info
  30834. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30835. return geometry;
  30836. };
  30837. Geometry.prototype.serialize = function () {
  30838. var serializationObject = {};
  30839. serializationObject.id = this.id;
  30840. serializationObject.updatable = this._updatable;
  30841. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30842. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30843. }
  30844. return serializationObject;
  30845. };
  30846. Geometry.prototype.toNumberArray = function (origin) {
  30847. if (Array.isArray(origin)) {
  30848. return origin;
  30849. }
  30850. else {
  30851. return Array.prototype.slice.call(origin);
  30852. }
  30853. };
  30854. Geometry.prototype.serializeVerticeData = function () {
  30855. var serializationObject = this.serialize();
  30856. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30857. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  30858. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30859. serializationObject.positions._updatable = true;
  30860. }
  30861. }
  30862. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30863. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  30864. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30865. serializationObject.normals._updatable = true;
  30866. }
  30867. }
  30868. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30869. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  30870. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  30871. serializationObject.uvs._updatable = true;
  30872. }
  30873. }
  30874. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30875. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  30876. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  30877. serializationObject.uv2s._updatable = true;
  30878. }
  30879. }
  30880. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30881. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  30882. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  30883. serializationObject.uv3s._updatable = true;
  30884. }
  30885. }
  30886. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30887. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  30888. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  30889. serializationObject.uv4s._updatable = true;
  30890. }
  30891. }
  30892. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30893. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  30894. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  30895. serializationObject.uv5s._updatable = true;
  30896. }
  30897. }
  30898. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30899. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  30900. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  30901. serializationObject.uv6s._updatable = true;
  30902. }
  30903. }
  30904. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30905. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  30906. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  30907. serializationObject.colors._updatable = true;
  30908. }
  30909. }
  30910. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30911. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  30912. serializationObject.matricesIndices._isExpanded = true;
  30913. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30914. serializationObject.matricesIndices._updatable = true;
  30915. }
  30916. }
  30917. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30918. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  30919. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30920. serializationObject.matricesWeights._updatable = true;
  30921. }
  30922. }
  30923. serializationObject.indices = this.toNumberArray(this.getIndices());
  30924. return serializationObject;
  30925. };
  30926. // Statics
  30927. Geometry.ExtractFromMesh = function (mesh, id) {
  30928. var geometry = mesh._geometry;
  30929. if (!geometry) {
  30930. return null;
  30931. }
  30932. return geometry.copy(id);
  30933. };
  30934. /**
  30935. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  30936. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  30937. * Be aware Math.random() could cause collisions, but:
  30938. * "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"
  30939. */
  30940. Geometry.RandomId = function () {
  30941. return BABYLON.Tools.RandomId();
  30942. };
  30943. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  30944. var scene = mesh.getScene();
  30945. // Geometry
  30946. var geometryId = parsedGeometry.geometryId;
  30947. if (geometryId) {
  30948. var geometry = scene.getGeometryByID(geometryId);
  30949. if (geometry) {
  30950. geometry.applyToMesh(mesh);
  30951. }
  30952. }
  30953. else if (parsedGeometry instanceof ArrayBuffer) {
  30954. var binaryInfo = mesh._binaryInfo;
  30955. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  30956. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  30957. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  30958. }
  30959. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  30960. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  30961. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  30962. }
  30963. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  30964. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  30965. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  30966. }
  30967. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  30968. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  30969. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  30970. }
  30971. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  30972. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  30973. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  30974. }
  30975. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  30976. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  30977. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  30978. }
  30979. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  30980. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  30981. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  30982. }
  30983. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  30984. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  30985. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  30986. }
  30987. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  30988. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  30989. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  30990. }
  30991. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  30992. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  30993. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  30994. }
  30995. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  30996. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  30997. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  30998. }
  30999. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31000. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31001. mesh.setIndices(indicesData, null);
  31002. }
  31003. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31004. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31005. mesh.subMeshes = [];
  31006. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31007. var materialIndex = subMeshesData[(i * 5) + 0];
  31008. var verticesStart = subMeshesData[(i * 5) + 1];
  31009. var verticesCount = subMeshesData[(i * 5) + 2];
  31010. var indexStart = subMeshesData[(i * 5) + 3];
  31011. var indexCount = subMeshesData[(i * 5) + 4];
  31012. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31013. }
  31014. }
  31015. }
  31016. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31017. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31018. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31019. if (parsedGeometry.uvs) {
  31020. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31021. }
  31022. if (parsedGeometry.uvs2) {
  31023. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31024. }
  31025. if (parsedGeometry.uvs3) {
  31026. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31027. }
  31028. if (parsedGeometry.uvs4) {
  31029. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31030. }
  31031. if (parsedGeometry.uvs5) {
  31032. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31033. }
  31034. if (parsedGeometry.uvs6) {
  31035. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31036. }
  31037. if (parsedGeometry.colors) {
  31038. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31039. }
  31040. if (parsedGeometry.matricesIndices) {
  31041. if (!parsedGeometry.matricesIndices._isExpanded) {
  31042. var floatIndices = [];
  31043. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31044. var matricesIndex = parsedGeometry.matricesIndices[i];
  31045. floatIndices.push(matricesIndex & 0x000000FF);
  31046. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31047. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31048. floatIndices.push(matricesIndex >> 24);
  31049. }
  31050. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31051. }
  31052. else {
  31053. delete parsedGeometry.matricesIndices._isExpanded;
  31054. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31055. }
  31056. }
  31057. if (parsedGeometry.matricesIndicesExtra) {
  31058. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31059. var floatIndices = [];
  31060. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31061. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31062. floatIndices.push(matricesIndex & 0x000000FF);
  31063. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31064. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31065. floatIndices.push(matricesIndex >> 24);
  31066. }
  31067. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31068. }
  31069. else {
  31070. delete parsedGeometry.matricesIndices._isExpanded;
  31071. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31072. }
  31073. }
  31074. if (parsedGeometry.matricesWeights) {
  31075. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31076. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31077. }
  31078. if (parsedGeometry.matricesWeightsExtra) {
  31079. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31080. }
  31081. mesh.setIndices(parsedGeometry.indices, null);
  31082. }
  31083. // SubMeshes
  31084. if (parsedGeometry.subMeshes) {
  31085. mesh.subMeshes = [];
  31086. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31087. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31088. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31089. }
  31090. }
  31091. // Flat shading
  31092. if (mesh._shouldGenerateFlatShading) {
  31093. mesh.convertToFlatShadedMesh();
  31094. delete mesh._shouldGenerateFlatShading;
  31095. }
  31096. // Update
  31097. mesh.computeWorldMatrix(true);
  31098. // Octree
  31099. if (scene['_selectionOctree']) {
  31100. scene['_selectionOctree'].addMesh(mesh);
  31101. }
  31102. };
  31103. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31104. var epsilon = 1e-3;
  31105. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31106. return;
  31107. }
  31108. var noInfluenceBoneIndex = 0.0;
  31109. if (parsedGeometry.skeletonId > -1) {
  31110. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31111. if (!skeleton) {
  31112. return;
  31113. }
  31114. noInfluenceBoneIndex = skeleton.bones.length;
  31115. }
  31116. else {
  31117. return;
  31118. }
  31119. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31120. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31121. var matricesWeights = parsedGeometry.matricesWeights;
  31122. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31123. var influencers = parsedGeometry.numBoneInfluencer;
  31124. var size = matricesWeights.length;
  31125. for (var i = 0; i < size; i += 4) {
  31126. var weight = 0.0;
  31127. var firstZeroWeight = -1;
  31128. for (var j = 0; j < 4; j++) {
  31129. var w = matricesWeights[i + j];
  31130. weight += w;
  31131. if (w < epsilon && firstZeroWeight < 0) {
  31132. firstZeroWeight = j;
  31133. }
  31134. }
  31135. if (matricesWeightsExtra) {
  31136. for (var j = 0; j < 4; j++) {
  31137. var w = matricesWeightsExtra[i + j];
  31138. weight += w;
  31139. if (w < epsilon && firstZeroWeight < 0) {
  31140. firstZeroWeight = j + 4;
  31141. }
  31142. }
  31143. }
  31144. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31145. firstZeroWeight = influencers - 1;
  31146. }
  31147. if (weight > epsilon) {
  31148. var mweight = 1.0 / weight;
  31149. for (var j = 0; j < 4; j++) {
  31150. matricesWeights[i + j] *= mweight;
  31151. }
  31152. if (matricesWeightsExtra) {
  31153. for (var j = 0; j < 4; j++) {
  31154. matricesWeightsExtra[i + j] *= mweight;
  31155. }
  31156. }
  31157. }
  31158. else {
  31159. if (firstZeroWeight >= 4) {
  31160. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31161. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31162. }
  31163. else {
  31164. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31165. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31166. }
  31167. }
  31168. }
  31169. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31170. if (parsedGeometry.matricesWeightsExtra) {
  31171. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31172. }
  31173. };
  31174. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31175. if (scene.getGeometryByID(parsedVertexData.id)) {
  31176. return null; // null since geometry could be something else than a box...
  31177. }
  31178. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31179. if (BABYLON.Tags) {
  31180. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31181. }
  31182. if (parsedVertexData.delayLoadingFile) {
  31183. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31184. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31185. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31186. geometry._delayInfo = [];
  31187. if (parsedVertexData.hasUVs) {
  31188. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31189. }
  31190. if (parsedVertexData.hasUVs2) {
  31191. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31192. }
  31193. if (parsedVertexData.hasUVs3) {
  31194. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31195. }
  31196. if (parsedVertexData.hasUVs4) {
  31197. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31198. }
  31199. if (parsedVertexData.hasUVs5) {
  31200. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31201. }
  31202. if (parsedVertexData.hasUVs6) {
  31203. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31204. }
  31205. if (parsedVertexData.hasColors) {
  31206. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31207. }
  31208. if (parsedVertexData.hasMatricesIndices) {
  31209. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31210. }
  31211. if (parsedVertexData.hasMatricesWeights) {
  31212. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31213. }
  31214. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31215. }
  31216. else {
  31217. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31218. }
  31219. scene.pushGeometry(geometry, true);
  31220. return geometry;
  31221. };
  31222. return Geometry;
  31223. }());
  31224. BABYLON.Geometry = Geometry;
  31225. /////// Primitives //////////////////////////////////////////////
  31226. (function (Geometry) {
  31227. var Primitives;
  31228. (function (Primitives) {
  31229. /// Abstract class
  31230. var _Primitive = /** @class */ (function (_super) {
  31231. __extends(_Primitive, _super);
  31232. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31233. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31234. if (mesh === void 0) { mesh = null; }
  31235. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31236. _this._canBeRegenerated = _canBeRegenerated;
  31237. _this._beingRegenerated = true;
  31238. _this.regenerate();
  31239. _this._beingRegenerated = false;
  31240. return _this;
  31241. }
  31242. _Primitive.prototype.canBeRegenerated = function () {
  31243. return this._canBeRegenerated;
  31244. };
  31245. _Primitive.prototype.regenerate = function () {
  31246. if (!this._canBeRegenerated) {
  31247. return;
  31248. }
  31249. this._beingRegenerated = true;
  31250. this.setAllVerticesData(this._regenerateVertexData(), false);
  31251. this._beingRegenerated = false;
  31252. };
  31253. _Primitive.prototype.asNewGeometry = function (id) {
  31254. return _super.prototype.copy.call(this, id);
  31255. };
  31256. // overrides
  31257. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31258. if (!this._beingRegenerated) {
  31259. return;
  31260. }
  31261. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31262. };
  31263. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31264. if (!this._beingRegenerated) {
  31265. return;
  31266. }
  31267. _super.prototype.setVerticesData.call(this, kind, data, false);
  31268. };
  31269. // to override
  31270. // protected
  31271. _Primitive.prototype._regenerateVertexData = function () {
  31272. throw new Error("Abstract method");
  31273. };
  31274. _Primitive.prototype.copy = function (id) {
  31275. throw new Error("Must be overriden in sub-classes.");
  31276. };
  31277. _Primitive.prototype.serialize = function () {
  31278. var serializationObject = _super.prototype.serialize.call(this);
  31279. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31280. return serializationObject;
  31281. };
  31282. return _Primitive;
  31283. }(Geometry));
  31284. Primitives._Primitive = _Primitive;
  31285. var Ribbon = /** @class */ (function (_super) {
  31286. __extends(Ribbon, _super);
  31287. // Members
  31288. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31289. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31290. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31291. _this.pathArray = pathArray;
  31292. _this.closeArray = closeArray;
  31293. _this.closePath = closePath;
  31294. _this.offset = offset;
  31295. _this.side = side;
  31296. return _this;
  31297. }
  31298. Ribbon.prototype._regenerateVertexData = function () {
  31299. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31300. };
  31301. Ribbon.prototype.copy = function (id) {
  31302. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31303. };
  31304. return Ribbon;
  31305. }(_Primitive));
  31306. Primitives.Ribbon = Ribbon;
  31307. var Box = /** @class */ (function (_super) {
  31308. __extends(Box, _super);
  31309. // Members
  31310. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31311. if (mesh === void 0) { mesh = null; }
  31312. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31313. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31314. _this.size = size;
  31315. _this.side = side;
  31316. return _this;
  31317. }
  31318. Box.prototype._regenerateVertexData = function () {
  31319. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31320. };
  31321. Box.prototype.copy = function (id) {
  31322. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31323. };
  31324. Box.prototype.serialize = function () {
  31325. var serializationObject = _super.prototype.serialize.call(this);
  31326. serializationObject.size = this.size;
  31327. return serializationObject;
  31328. };
  31329. Box.Parse = function (parsedBox, scene) {
  31330. if (scene.getGeometryByID(parsedBox.id)) {
  31331. return null; // null since geometry could be something else than a box...
  31332. }
  31333. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31334. if (BABYLON.Tags) {
  31335. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31336. }
  31337. scene.pushGeometry(box, true);
  31338. return box;
  31339. };
  31340. return Box;
  31341. }(_Primitive));
  31342. Primitives.Box = Box;
  31343. var Sphere = /** @class */ (function (_super) {
  31344. __extends(Sphere, _super);
  31345. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31346. if (mesh === void 0) { mesh = null; }
  31347. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31348. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31349. _this.segments = segments;
  31350. _this.diameter = diameter;
  31351. _this.side = side;
  31352. return _this;
  31353. }
  31354. Sphere.prototype._regenerateVertexData = function () {
  31355. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31356. };
  31357. Sphere.prototype.copy = function (id) {
  31358. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31359. };
  31360. Sphere.prototype.serialize = function () {
  31361. var serializationObject = _super.prototype.serialize.call(this);
  31362. serializationObject.segments = this.segments;
  31363. serializationObject.diameter = this.diameter;
  31364. return serializationObject;
  31365. };
  31366. Sphere.Parse = function (parsedSphere, scene) {
  31367. if (scene.getGeometryByID(parsedSphere.id)) {
  31368. return null; // null since geometry could be something else than a sphere...
  31369. }
  31370. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31371. if (BABYLON.Tags) {
  31372. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31373. }
  31374. scene.pushGeometry(sphere, true);
  31375. return sphere;
  31376. };
  31377. return Sphere;
  31378. }(_Primitive));
  31379. Primitives.Sphere = Sphere;
  31380. var Disc = /** @class */ (function (_super) {
  31381. __extends(Disc, _super);
  31382. // Members
  31383. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31384. if (mesh === void 0) { mesh = null; }
  31385. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31386. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31387. _this.radius = radius;
  31388. _this.tessellation = tessellation;
  31389. _this.side = side;
  31390. return _this;
  31391. }
  31392. Disc.prototype._regenerateVertexData = function () {
  31393. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31394. };
  31395. Disc.prototype.copy = function (id) {
  31396. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31397. };
  31398. return Disc;
  31399. }(_Primitive));
  31400. Primitives.Disc = Disc;
  31401. var Cylinder = /** @class */ (function (_super) {
  31402. __extends(Cylinder, _super);
  31403. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31404. if (subdivisions === void 0) { subdivisions = 1; }
  31405. if (mesh === void 0) { mesh = null; }
  31406. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31407. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31408. _this.height = height;
  31409. _this.diameterTop = diameterTop;
  31410. _this.diameterBottom = diameterBottom;
  31411. _this.tessellation = tessellation;
  31412. _this.subdivisions = subdivisions;
  31413. _this.side = side;
  31414. return _this;
  31415. }
  31416. Cylinder.prototype._regenerateVertexData = function () {
  31417. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31418. };
  31419. Cylinder.prototype.copy = function (id) {
  31420. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31421. };
  31422. Cylinder.prototype.serialize = function () {
  31423. var serializationObject = _super.prototype.serialize.call(this);
  31424. serializationObject.height = this.height;
  31425. serializationObject.diameterTop = this.diameterTop;
  31426. serializationObject.diameterBottom = this.diameterBottom;
  31427. serializationObject.tessellation = this.tessellation;
  31428. return serializationObject;
  31429. };
  31430. Cylinder.Parse = function (parsedCylinder, scene) {
  31431. if (scene.getGeometryByID(parsedCylinder.id)) {
  31432. return null; // null since geometry could be something else than a cylinder...
  31433. }
  31434. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31435. if (BABYLON.Tags) {
  31436. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31437. }
  31438. scene.pushGeometry(cylinder, true);
  31439. return cylinder;
  31440. };
  31441. return Cylinder;
  31442. }(_Primitive));
  31443. Primitives.Cylinder = Cylinder;
  31444. var Torus = /** @class */ (function (_super) {
  31445. __extends(Torus, _super);
  31446. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31447. if (mesh === void 0) { mesh = null; }
  31448. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31449. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31450. _this.diameter = diameter;
  31451. _this.thickness = thickness;
  31452. _this.tessellation = tessellation;
  31453. _this.side = side;
  31454. return _this;
  31455. }
  31456. Torus.prototype._regenerateVertexData = function () {
  31457. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31458. };
  31459. Torus.prototype.copy = function (id) {
  31460. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31461. };
  31462. Torus.prototype.serialize = function () {
  31463. var serializationObject = _super.prototype.serialize.call(this);
  31464. serializationObject.diameter = this.diameter;
  31465. serializationObject.thickness = this.thickness;
  31466. serializationObject.tessellation = this.tessellation;
  31467. return serializationObject;
  31468. };
  31469. Torus.Parse = function (parsedTorus, scene) {
  31470. if (scene.getGeometryByID(parsedTorus.id)) {
  31471. return null; // null since geometry could be something else than a torus...
  31472. }
  31473. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31474. if (BABYLON.Tags) {
  31475. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31476. }
  31477. scene.pushGeometry(torus, true);
  31478. return torus;
  31479. };
  31480. return Torus;
  31481. }(_Primitive));
  31482. Primitives.Torus = Torus;
  31483. var Ground = /** @class */ (function (_super) {
  31484. __extends(Ground, _super);
  31485. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31486. if (mesh === void 0) { mesh = null; }
  31487. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31488. _this.width = width;
  31489. _this.height = height;
  31490. _this.subdivisions = subdivisions;
  31491. return _this;
  31492. }
  31493. Ground.prototype._regenerateVertexData = function () {
  31494. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31495. };
  31496. Ground.prototype.copy = function (id) {
  31497. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31498. };
  31499. Ground.prototype.serialize = function () {
  31500. var serializationObject = _super.prototype.serialize.call(this);
  31501. serializationObject.width = this.width;
  31502. serializationObject.height = this.height;
  31503. serializationObject.subdivisions = this.subdivisions;
  31504. return serializationObject;
  31505. };
  31506. Ground.Parse = function (parsedGround, scene) {
  31507. if (scene.getGeometryByID(parsedGround.id)) {
  31508. return null; // null since geometry could be something else than a ground...
  31509. }
  31510. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31511. if (BABYLON.Tags) {
  31512. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31513. }
  31514. scene.pushGeometry(ground, true);
  31515. return ground;
  31516. };
  31517. return Ground;
  31518. }(_Primitive));
  31519. Primitives.Ground = Ground;
  31520. var TiledGround = /** @class */ (function (_super) {
  31521. __extends(TiledGround, _super);
  31522. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31523. if (mesh === void 0) { mesh = null; }
  31524. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31525. _this.xmin = xmin;
  31526. _this.zmin = zmin;
  31527. _this.xmax = xmax;
  31528. _this.zmax = zmax;
  31529. _this.subdivisions = subdivisions;
  31530. _this.precision = precision;
  31531. return _this;
  31532. }
  31533. TiledGround.prototype._regenerateVertexData = function () {
  31534. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31535. };
  31536. TiledGround.prototype.copy = function (id) {
  31537. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31538. };
  31539. return TiledGround;
  31540. }(_Primitive));
  31541. Primitives.TiledGround = TiledGround;
  31542. var Plane = /** @class */ (function (_super) {
  31543. __extends(Plane, _super);
  31544. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31545. if (mesh === void 0) { mesh = null; }
  31546. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31547. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31548. _this.size = size;
  31549. _this.side = side;
  31550. return _this;
  31551. }
  31552. Plane.prototype._regenerateVertexData = function () {
  31553. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31554. };
  31555. Plane.prototype.copy = function (id) {
  31556. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31557. };
  31558. Plane.prototype.serialize = function () {
  31559. var serializationObject = _super.prototype.serialize.call(this);
  31560. serializationObject.size = this.size;
  31561. return serializationObject;
  31562. };
  31563. Plane.Parse = function (parsedPlane, scene) {
  31564. if (scene.getGeometryByID(parsedPlane.id)) {
  31565. return null; // null since geometry could be something else than a ground...
  31566. }
  31567. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31568. if (BABYLON.Tags) {
  31569. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31570. }
  31571. scene.pushGeometry(plane, true);
  31572. return plane;
  31573. };
  31574. return Plane;
  31575. }(_Primitive));
  31576. Primitives.Plane = Plane;
  31577. var TorusKnot = /** @class */ (function (_super) {
  31578. __extends(TorusKnot, _super);
  31579. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31580. if (mesh === void 0) { mesh = null; }
  31581. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31582. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31583. _this.radius = radius;
  31584. _this.tube = tube;
  31585. _this.radialSegments = radialSegments;
  31586. _this.tubularSegments = tubularSegments;
  31587. _this.p = p;
  31588. _this.q = q;
  31589. _this.side = side;
  31590. return _this;
  31591. }
  31592. TorusKnot.prototype._regenerateVertexData = function () {
  31593. 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 });
  31594. };
  31595. TorusKnot.prototype.copy = function (id) {
  31596. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31597. };
  31598. TorusKnot.prototype.serialize = function () {
  31599. var serializationObject = _super.prototype.serialize.call(this);
  31600. serializationObject.radius = this.radius;
  31601. serializationObject.tube = this.tube;
  31602. serializationObject.radialSegments = this.radialSegments;
  31603. serializationObject.tubularSegments = this.tubularSegments;
  31604. serializationObject.p = this.p;
  31605. serializationObject.q = this.q;
  31606. return serializationObject;
  31607. };
  31608. ;
  31609. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31610. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31611. return null; // null since geometry could be something else than a ground...
  31612. }
  31613. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31614. if (BABYLON.Tags) {
  31615. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31616. }
  31617. scene.pushGeometry(torusKnot, true);
  31618. return torusKnot;
  31619. };
  31620. return TorusKnot;
  31621. }(_Primitive));
  31622. Primitives.TorusKnot = TorusKnot;
  31623. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31624. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31625. })(BABYLON || (BABYLON = {}));
  31626. //# sourceMappingURL=babylon.geometry.js.map
  31627. var BABYLON;
  31628. (function (BABYLON) {
  31629. var PostProcessManager = /** @class */ (function () {
  31630. function PostProcessManager(scene) {
  31631. this._vertexBuffers = {};
  31632. this._scene = scene;
  31633. }
  31634. PostProcessManager.prototype._prepareBuffers = function () {
  31635. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31636. return;
  31637. }
  31638. // VBO
  31639. var vertices = [];
  31640. vertices.push(1, 1);
  31641. vertices.push(-1, 1);
  31642. vertices.push(-1, -1);
  31643. vertices.push(1, -1);
  31644. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31645. this._buildIndexBuffer();
  31646. };
  31647. PostProcessManager.prototype._buildIndexBuffer = function () {
  31648. // Indices
  31649. var indices = [];
  31650. indices.push(0);
  31651. indices.push(1);
  31652. indices.push(2);
  31653. indices.push(0);
  31654. indices.push(2);
  31655. indices.push(3);
  31656. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31657. };
  31658. PostProcessManager.prototype._rebuild = function () {
  31659. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31660. if (!vb) {
  31661. return;
  31662. }
  31663. vb._rebuild();
  31664. this._buildIndexBuffer();
  31665. };
  31666. // Methods
  31667. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  31668. if (sourceTexture === void 0) { sourceTexture = null; }
  31669. if (postProcesses === void 0) { postProcesses = null; }
  31670. var camera = this._scene.activeCamera;
  31671. if (!camera) {
  31672. return false;
  31673. }
  31674. var postProcesses = postProcesses || camera._postProcesses;
  31675. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31676. return false;
  31677. }
  31678. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  31679. return true;
  31680. };
  31681. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  31682. if (targetTexture === void 0) { targetTexture = null; }
  31683. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31684. if (!this._scene.activeCamera) {
  31685. return;
  31686. }
  31687. var engine = this._scene.getEngine();
  31688. for (var index = 0; index < postProcesses.length; index++) {
  31689. if (index < postProcesses.length - 1) {
  31690. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31691. }
  31692. else {
  31693. if (targetTexture) {
  31694. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  31695. }
  31696. else {
  31697. engine.restoreDefaultFramebuffer();
  31698. }
  31699. }
  31700. var pp = postProcesses[index];
  31701. var effect = pp.apply();
  31702. if (effect) {
  31703. pp.onBeforeRenderObservable.notifyObservers(effect);
  31704. // VBOs
  31705. this._prepareBuffers();
  31706. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31707. // Draw order
  31708. engine.draw(true, 0, 6);
  31709. pp.onAfterRenderObservable.notifyObservers(effect);
  31710. }
  31711. }
  31712. // Restore depth buffer
  31713. engine.setDepthBuffer(true);
  31714. engine.setDepthWrite(true);
  31715. };
  31716. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  31717. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31718. var camera = this._scene.activeCamera;
  31719. if (!camera) {
  31720. return;
  31721. }
  31722. postProcesses = postProcesses || camera._postProcesses;
  31723. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31724. return;
  31725. }
  31726. var engine = this._scene.getEngine();
  31727. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31728. if (index < len - 1) {
  31729. postProcesses[index + 1].activate(camera, targetTexture);
  31730. }
  31731. else {
  31732. if (targetTexture) {
  31733. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  31734. }
  31735. else {
  31736. engine.restoreDefaultFramebuffer();
  31737. }
  31738. }
  31739. if (doNotPresent) {
  31740. break;
  31741. }
  31742. var pp = postProcesses[index];
  31743. var effect = pp.apply();
  31744. if (effect) {
  31745. pp.onBeforeRenderObservable.notifyObservers(effect);
  31746. // VBOs
  31747. this._prepareBuffers();
  31748. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31749. // Draw order
  31750. engine.draw(true, 0, 6);
  31751. pp.onAfterRenderObservable.notifyObservers(effect);
  31752. }
  31753. }
  31754. // Restore states
  31755. engine.setDepthBuffer(true);
  31756. engine.setDepthWrite(true);
  31757. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31758. };
  31759. PostProcessManager.prototype.dispose = function () {
  31760. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31761. if (buffer) {
  31762. buffer.dispose();
  31763. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31764. }
  31765. if (this._indexBuffer) {
  31766. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31767. this._indexBuffer = null;
  31768. }
  31769. };
  31770. return PostProcessManager;
  31771. }());
  31772. BABYLON.PostProcessManager = PostProcessManager;
  31773. })(BABYLON || (BABYLON = {}));
  31774. //# sourceMappingURL=babylon.postProcessManager.js.map
  31775. var BABYLON;
  31776. (function (BABYLON) {
  31777. /**
  31778. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  31779. */
  31780. var PerformanceMonitor = /** @class */ (function () {
  31781. /**
  31782. * constructor
  31783. * @param frameSampleSize The number of samples required to saturate the sliding window
  31784. */
  31785. function PerformanceMonitor(frameSampleSize) {
  31786. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  31787. this._enabled = true;
  31788. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  31789. }
  31790. /**
  31791. * Samples current frame
  31792. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  31793. */
  31794. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  31795. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  31796. if (!this._enabled)
  31797. return;
  31798. if (this._lastFrameTimeMs != null) {
  31799. var dt = timeMs - this._lastFrameTimeMs;
  31800. this._rollingFrameTime.add(dt);
  31801. }
  31802. this._lastFrameTimeMs = timeMs;
  31803. };
  31804. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  31805. /**
  31806. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31807. * @return Average frame time in milliseconds
  31808. */
  31809. get: function () {
  31810. return this._rollingFrameTime.average;
  31811. },
  31812. enumerable: true,
  31813. configurable: true
  31814. });
  31815. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  31816. /**
  31817. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31818. * @return Frame time variance in milliseconds squared
  31819. */
  31820. get: function () {
  31821. return this._rollingFrameTime.variance;
  31822. },
  31823. enumerable: true,
  31824. configurable: true
  31825. });
  31826. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  31827. /**
  31828. * Returns the frame time of the most recent frame
  31829. * @return Frame time in milliseconds
  31830. */
  31831. get: function () {
  31832. return this._rollingFrameTime.history(0);
  31833. },
  31834. enumerable: true,
  31835. configurable: true
  31836. });
  31837. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  31838. /**
  31839. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  31840. * @return Framerate in frames per second
  31841. */
  31842. get: function () {
  31843. return 1000.0 / this._rollingFrameTime.average;
  31844. },
  31845. enumerable: true,
  31846. configurable: true
  31847. });
  31848. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  31849. /**
  31850. * Returns the average framerate in frames per second using the most recent frame time
  31851. * @return Framerate in frames per second
  31852. */
  31853. get: function () {
  31854. var history = this._rollingFrameTime.history(0);
  31855. if (history === 0) {
  31856. return 0;
  31857. }
  31858. return 1000.0 / history;
  31859. },
  31860. enumerable: true,
  31861. configurable: true
  31862. });
  31863. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  31864. /**
  31865. * Returns true if enough samples have been taken to completely fill the sliding window
  31866. * @return true if saturated
  31867. */
  31868. get: function () {
  31869. return this._rollingFrameTime.isSaturated();
  31870. },
  31871. enumerable: true,
  31872. configurable: true
  31873. });
  31874. /**
  31875. * Enables contributions to the sliding window sample set
  31876. */
  31877. PerformanceMonitor.prototype.enable = function () {
  31878. this._enabled = true;
  31879. };
  31880. /**
  31881. * Disables contributions to the sliding window sample set
  31882. * Samples will not be interpolated over the disabled period
  31883. */
  31884. PerformanceMonitor.prototype.disable = function () {
  31885. this._enabled = false;
  31886. //clear last sample to avoid interpolating over the disabled period when next enabled
  31887. this._lastFrameTimeMs = null;
  31888. this._lastChangeTimeMs = null;
  31889. };
  31890. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  31891. /**
  31892. * Returns true if sampling is enabled
  31893. * @return true if enabled
  31894. */
  31895. get: function () {
  31896. return this._enabled;
  31897. },
  31898. enumerable: true,
  31899. configurable: true
  31900. });
  31901. /**
  31902. * Resets performance monitor
  31903. */
  31904. PerformanceMonitor.prototype.reset = function () {
  31905. //clear last sample to avoid interpolating over the disabled period when next enabled
  31906. this._lastFrameTimeMs = null;
  31907. this._lastChangeTimeMs = null;
  31908. //wipe record
  31909. this._rollingFrameTime.reset();
  31910. };
  31911. return PerformanceMonitor;
  31912. }());
  31913. BABYLON.PerformanceMonitor = PerformanceMonitor;
  31914. /**
  31915. * RollingAverage
  31916. *
  31917. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  31918. */
  31919. var RollingAverage = /** @class */ (function () {
  31920. /**
  31921. * constructor
  31922. * @param length The number of samples required to saturate the sliding window
  31923. */
  31924. function RollingAverage(length) {
  31925. this._samples = new Array(length);
  31926. this.reset();
  31927. }
  31928. /**
  31929. * Adds a sample to the sample set
  31930. * @param v The sample value
  31931. */
  31932. RollingAverage.prototype.add = function (v) {
  31933. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  31934. var delta;
  31935. //we need to check if we've already wrapped round
  31936. if (this.isSaturated()) {
  31937. //remove bottom of stack from mean
  31938. var bottomValue = this._samples[this._pos];
  31939. delta = bottomValue - this.average;
  31940. this.average -= delta / (this._sampleCount - 1);
  31941. this._m2 -= delta * (bottomValue - this.average);
  31942. }
  31943. else {
  31944. this._sampleCount++;
  31945. }
  31946. //add new value to mean
  31947. delta = v - this.average;
  31948. this.average += delta / (this._sampleCount);
  31949. this._m2 += delta * (v - this.average);
  31950. //set the new variance
  31951. this.variance = this._m2 / (this._sampleCount - 1);
  31952. this._samples[this._pos] = v;
  31953. this._pos++;
  31954. this._pos %= this._samples.length; //positive wrap around
  31955. };
  31956. /**
  31957. * Returns previously added values or null if outside of history or outside the sliding window domain
  31958. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  31959. * @return Value previously recorded with add() or null if outside of range
  31960. */
  31961. RollingAverage.prototype.history = function (i) {
  31962. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  31963. return 0;
  31964. }
  31965. var i0 = this._wrapPosition(this._pos - 1.0);
  31966. return this._samples[this._wrapPosition(i0 - i)];
  31967. };
  31968. /**
  31969. * Returns true if enough samples have been taken to completely fill the sliding window
  31970. * @return true if sample-set saturated
  31971. */
  31972. RollingAverage.prototype.isSaturated = function () {
  31973. return this._sampleCount >= this._samples.length;
  31974. };
  31975. /**
  31976. * Resets the rolling average (equivalent to 0 samples taken so far)
  31977. */
  31978. RollingAverage.prototype.reset = function () {
  31979. this.average = 0;
  31980. this.variance = 0;
  31981. this._sampleCount = 0;
  31982. this._pos = 0;
  31983. this._m2 = 0;
  31984. };
  31985. /**
  31986. * Wraps a value around the sample range boundaries
  31987. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  31988. * @return Wrapped position in sample range
  31989. */
  31990. RollingAverage.prototype._wrapPosition = function (i) {
  31991. var max = this._samples.length;
  31992. return ((i % max) + max) % max;
  31993. };
  31994. return RollingAverage;
  31995. }());
  31996. BABYLON.RollingAverage = RollingAverage;
  31997. })(BABYLON || (BABYLON = {}));
  31998. //# sourceMappingURL=babylon.performanceMonitor.js.map
  31999. var BABYLON;
  32000. (function (BABYLON) {
  32001. /**
  32002. * This groups together the common properties used for image processing either in direct forward pass
  32003. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32004. * or not.
  32005. */
  32006. var ImageProcessingConfiguration = /** @class */ (function () {
  32007. function ImageProcessingConfiguration() {
  32008. /**
  32009. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32010. */
  32011. this.colorCurves = new BABYLON.ColorCurves();
  32012. this._colorCurvesEnabled = false;
  32013. this._colorGradingEnabled = false;
  32014. this._colorGradingWithGreenDepth = true;
  32015. this._colorGradingBGR = true;
  32016. this._exposure = 1.0;
  32017. this._toneMappingEnabled = false;
  32018. this._contrast = 1.0;
  32019. /**
  32020. * Vignette stretch size.
  32021. */
  32022. this.vignetteStretch = 0;
  32023. /**
  32024. * Vignette centre X Offset.
  32025. */
  32026. this.vignetteCentreX = 0;
  32027. /**
  32028. * Vignette centre Y Offset.
  32029. */
  32030. this.vignetteCentreY = 0;
  32031. /**
  32032. * Vignette weight or intensity of the vignette effect.
  32033. */
  32034. this.vignetteWeight = 1.5;
  32035. /**
  32036. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32037. * if vignetteEnabled is set to true.
  32038. */
  32039. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32040. /**
  32041. * Camera field of view used by the Vignette effect.
  32042. */
  32043. this.vignetteCameraFov = 0.5;
  32044. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32045. this._vignetteEnabled = false;
  32046. this._applyByPostProcess = false;
  32047. /**
  32048. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32049. * @type {BABYLON.Observable}
  32050. */
  32051. this.onUpdateParameters = new BABYLON.Observable();
  32052. }
  32053. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32054. /**
  32055. * Gets wether the color curves effect is enabled.
  32056. */
  32057. get: function () {
  32058. return this._colorCurvesEnabled;
  32059. },
  32060. /**
  32061. * Sets wether the color curves effect is enabled.
  32062. */
  32063. set: function (value) {
  32064. if (this._colorCurvesEnabled === value) {
  32065. return;
  32066. }
  32067. this._colorCurvesEnabled = value;
  32068. this._updateParameters();
  32069. },
  32070. enumerable: true,
  32071. configurable: true
  32072. });
  32073. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32074. /**
  32075. * Gets wether the color grading effect is enabled.
  32076. */
  32077. get: function () {
  32078. return this._colorGradingEnabled;
  32079. },
  32080. /**
  32081. * Sets wether the color grading effect is enabled.
  32082. */
  32083. set: function (value) {
  32084. if (this._colorGradingEnabled === value) {
  32085. return;
  32086. }
  32087. this._colorGradingEnabled = value;
  32088. this._updateParameters();
  32089. },
  32090. enumerable: true,
  32091. configurable: true
  32092. });
  32093. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32094. /**
  32095. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32096. */
  32097. get: function () {
  32098. return this._colorGradingWithGreenDepth;
  32099. },
  32100. /**
  32101. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32102. */
  32103. set: function (value) {
  32104. if (this._colorGradingWithGreenDepth === value) {
  32105. return;
  32106. }
  32107. this._colorGradingWithGreenDepth = value;
  32108. this._updateParameters();
  32109. },
  32110. enumerable: true,
  32111. configurable: true
  32112. });
  32113. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32114. /**
  32115. * Gets wether the color grading texture contains BGR values.
  32116. */
  32117. get: function () {
  32118. return this._colorGradingBGR;
  32119. },
  32120. /**
  32121. * Sets wether the color grading texture contains BGR values.
  32122. */
  32123. set: function (value) {
  32124. if (this._colorGradingBGR === value) {
  32125. return;
  32126. }
  32127. this._colorGradingBGR = value;
  32128. this._updateParameters();
  32129. },
  32130. enumerable: true,
  32131. configurable: true
  32132. });
  32133. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32134. /**
  32135. * Gets the Exposure used in the effect.
  32136. */
  32137. get: function () {
  32138. return this._exposure;
  32139. },
  32140. /**
  32141. * Sets the Exposure used in the effect.
  32142. */
  32143. set: function (value) {
  32144. if (this._exposure === value) {
  32145. return;
  32146. }
  32147. this._exposure = value;
  32148. this._updateParameters();
  32149. },
  32150. enumerable: true,
  32151. configurable: true
  32152. });
  32153. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32154. /**
  32155. * Gets wether the tone mapping effect is enabled.
  32156. */
  32157. get: function () {
  32158. return this._toneMappingEnabled;
  32159. },
  32160. /**
  32161. * Sets wether the tone mapping effect is enabled.
  32162. */
  32163. set: function (value) {
  32164. if (this._toneMappingEnabled === value) {
  32165. return;
  32166. }
  32167. this._toneMappingEnabled = value;
  32168. this._updateParameters();
  32169. },
  32170. enumerable: true,
  32171. configurable: true
  32172. });
  32173. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32174. /**
  32175. * Gets the contrast used in the effect.
  32176. */
  32177. get: function () {
  32178. return this._contrast;
  32179. },
  32180. /**
  32181. * Sets the contrast used in the effect.
  32182. */
  32183. set: function (value) {
  32184. if (this._contrast === value) {
  32185. return;
  32186. }
  32187. this._contrast = value;
  32188. this._updateParameters();
  32189. },
  32190. enumerable: true,
  32191. configurable: true
  32192. });
  32193. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32194. /**
  32195. * Gets the vignette blend mode allowing different kind of effect.
  32196. */
  32197. get: function () {
  32198. return this._vignetteBlendMode;
  32199. },
  32200. /**
  32201. * Sets the vignette blend mode allowing different kind of effect.
  32202. */
  32203. set: function (value) {
  32204. if (this._vignetteBlendMode === value) {
  32205. return;
  32206. }
  32207. this._vignetteBlendMode = value;
  32208. this._updateParameters();
  32209. },
  32210. enumerable: true,
  32211. configurable: true
  32212. });
  32213. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32214. /**
  32215. * Gets wether the vignette effect is enabled.
  32216. */
  32217. get: function () {
  32218. return this._vignetteEnabled;
  32219. },
  32220. /**
  32221. * Sets wether the vignette effect is enabled.
  32222. */
  32223. set: function (value) {
  32224. if (this._vignetteEnabled === value) {
  32225. return;
  32226. }
  32227. this._vignetteEnabled = value;
  32228. this._updateParameters();
  32229. },
  32230. enumerable: true,
  32231. configurable: true
  32232. });
  32233. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32234. /**
  32235. * Gets wether the image processing is applied through a post process or not.
  32236. */
  32237. get: function () {
  32238. return this._applyByPostProcess;
  32239. },
  32240. /**
  32241. * Sets wether the image processing is applied through a post process or not.
  32242. */
  32243. set: function (value) {
  32244. if (this._applyByPostProcess === value) {
  32245. return;
  32246. }
  32247. this._applyByPostProcess = value;
  32248. this._updateParameters();
  32249. },
  32250. enumerable: true,
  32251. configurable: true
  32252. });
  32253. /**
  32254. * Method called each time the image processing information changes requires to recompile the effect.
  32255. */
  32256. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32257. this.onUpdateParameters.notifyObservers(this);
  32258. };
  32259. ImageProcessingConfiguration.prototype.getClassName = function () {
  32260. return "ImageProcessingConfiguration";
  32261. };
  32262. /**
  32263. * Prepare the list of uniforms associated with the Image Processing effects.
  32264. * @param uniformsList The list of uniforms used in the effect
  32265. * @param defines the list of defines currently in use
  32266. */
  32267. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32268. if (defines.EXPOSURE) {
  32269. uniforms.push("exposureLinear");
  32270. }
  32271. if (defines.CONTRAST) {
  32272. uniforms.push("contrast");
  32273. }
  32274. if (defines.COLORGRADING) {
  32275. uniforms.push("colorTransformSettings");
  32276. }
  32277. if (defines.VIGNETTE) {
  32278. uniforms.push("vInverseScreenSize");
  32279. uniforms.push("vignetteSettings1");
  32280. uniforms.push("vignetteSettings2");
  32281. }
  32282. if (defines.COLORCURVES) {
  32283. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32284. }
  32285. };
  32286. /**
  32287. * Prepare the list of samplers associated with the Image Processing effects.
  32288. * @param uniformsList The list of uniforms used in the effect
  32289. * @param defines the list of defines currently in use
  32290. */
  32291. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32292. if (defines.COLORGRADING) {
  32293. samplersList.push("txColorTransform");
  32294. }
  32295. };
  32296. /**
  32297. * Prepare the list of defines associated to the shader.
  32298. * @param defines the list of defines to complete
  32299. */
  32300. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32301. if (forPostProcess === void 0) { forPostProcess = false; }
  32302. if (forPostProcess !== this.applyByPostProcess) {
  32303. defines.VIGNETTE = false;
  32304. defines.TONEMAPPING = false;
  32305. defines.CONTRAST = false;
  32306. defines.EXPOSURE = false;
  32307. defines.COLORCURVES = false;
  32308. defines.COLORGRADING = false;
  32309. defines.COLORGRADING3D = false;
  32310. defines.IMAGEPROCESSING = false;
  32311. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32312. return;
  32313. }
  32314. defines.VIGNETTE = this.vignetteEnabled;
  32315. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32316. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32317. defines.TONEMAPPING = this.toneMappingEnabled;
  32318. defines.CONTRAST = (this.contrast !== 1.0);
  32319. defines.EXPOSURE = (this.exposure !== 1.0);
  32320. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32321. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32322. if (defines.COLORGRADING) {
  32323. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32324. }
  32325. else {
  32326. defines.COLORGRADING3D = false;
  32327. }
  32328. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32329. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32330. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32331. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32332. };
  32333. /**
  32334. * Returns true if all the image processing information are ready.
  32335. */
  32336. ImageProcessingConfiguration.prototype.isReady = function () {
  32337. // Color Grading texure can not be none blocking.
  32338. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32339. };
  32340. /**
  32341. * Binds the image processing to the shader.
  32342. * @param effect The effect to bind to
  32343. */
  32344. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32345. if (aspectRatio === void 0) { aspectRatio = 1; }
  32346. // Color Curves
  32347. if (this._colorCurvesEnabled && this.colorCurves) {
  32348. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32349. }
  32350. // Vignette
  32351. if (this._vignetteEnabled) {
  32352. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32353. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32354. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32355. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32356. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32357. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32358. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32359. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32360. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32361. var vignettePower = -2.0 * this.vignetteWeight;
  32362. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32363. }
  32364. // Exposure
  32365. effect.setFloat("exposureLinear", this.exposure);
  32366. // Contrast
  32367. effect.setFloat("contrast", this.contrast);
  32368. // Color transform settings
  32369. if (this.colorGradingTexture) {
  32370. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32371. var textureSize = this.colorGradingTexture.getSize().height;
  32372. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32373. 0.5 / textureSize, // textureOffset
  32374. textureSize, // textureSize
  32375. this.colorGradingTexture.level // weight
  32376. );
  32377. }
  32378. };
  32379. /**
  32380. * Clones the current image processing instance.
  32381. * @return The cloned image processing
  32382. */
  32383. ImageProcessingConfiguration.prototype.clone = function () {
  32384. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32385. };
  32386. /**
  32387. * Serializes the current image processing instance to a json representation.
  32388. * @return a JSON representation
  32389. */
  32390. ImageProcessingConfiguration.prototype.serialize = function () {
  32391. return BABYLON.SerializationHelper.Serialize(this);
  32392. };
  32393. /**
  32394. * Parses the image processing from a json representation.
  32395. * @param source the JSON source to parse
  32396. * @return The parsed image processing
  32397. */
  32398. ImageProcessingConfiguration.Parse = function (source) {
  32399. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32400. };
  32401. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32402. /**
  32403. * Used to apply the vignette as a mix with the pixel color.
  32404. */
  32405. get: function () {
  32406. return this._VIGNETTEMODE_MULTIPLY;
  32407. },
  32408. enumerable: true,
  32409. configurable: true
  32410. });
  32411. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32412. /**
  32413. * Used to apply the vignette as a replacement of the pixel color.
  32414. */
  32415. get: function () {
  32416. return this._VIGNETTEMODE_OPAQUE;
  32417. },
  32418. enumerable: true,
  32419. configurable: true
  32420. });
  32421. // Static constants associated to the image processing.
  32422. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32423. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32424. __decorate([
  32425. BABYLON.serializeAsColorCurves()
  32426. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32427. __decorate([
  32428. BABYLON.serialize()
  32429. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  32430. __decorate([
  32431. BABYLON.serializeAsTexture()
  32432. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  32433. __decorate([
  32434. BABYLON.serialize()
  32435. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  32436. __decorate([
  32437. BABYLON.serialize()
  32438. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  32439. __decorate([
  32440. BABYLON.serialize()
  32441. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  32442. __decorate([
  32443. BABYLON.serialize()
  32444. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  32445. __decorate([
  32446. BABYLON.serialize()
  32447. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  32448. __decorate([
  32449. BABYLON.serialize()
  32450. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  32451. __decorate([
  32452. BABYLON.serialize()
  32453. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  32454. __decorate([
  32455. BABYLON.serialize()
  32456. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  32457. __decorate([
  32458. BABYLON.serialize()
  32459. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  32460. __decorate([
  32461. BABYLON.serialize()
  32462. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  32463. __decorate([
  32464. BABYLON.serializeAsColor4()
  32465. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  32466. __decorate([
  32467. BABYLON.serialize()
  32468. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  32469. __decorate([
  32470. BABYLON.serialize()
  32471. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  32472. __decorate([
  32473. BABYLON.serialize()
  32474. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  32475. __decorate([
  32476. BABYLON.serialize()
  32477. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  32478. return ImageProcessingConfiguration;
  32479. }());
  32480. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  32481. })(BABYLON || (BABYLON = {}));
  32482. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  32483. var BABYLON;
  32484. (function (BABYLON) {
  32485. /**
  32486. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  32487. * It can help converting any input color in a desired output one. This can then be used to create effects
  32488. * from sepia, black and white to sixties or futuristic rendering...
  32489. *
  32490. * The only supported format is currently 3dl.
  32491. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  32492. */
  32493. var ColorGradingTexture = /** @class */ (function (_super) {
  32494. __extends(ColorGradingTexture, _super);
  32495. /**
  32496. * Instantiates a ColorGradingTexture from the following parameters.
  32497. *
  32498. * @param url The location of the color gradind data (currently only supporting 3dl)
  32499. * @param scene The scene the texture will be used in
  32500. */
  32501. function ColorGradingTexture(url, scene) {
  32502. var _this = _super.call(this, scene) || this;
  32503. if (!url) {
  32504. return _this;
  32505. }
  32506. _this._engine = scene.getEngine();
  32507. _this._textureMatrix = BABYLON.Matrix.Identity();
  32508. _this.name = url;
  32509. _this.url = url;
  32510. _this.hasAlpha = false;
  32511. _this.isCube = false;
  32512. _this.is3D = _this._engine.webGLVersion > 1;
  32513. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32514. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32515. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32516. _this.anisotropicFilteringLevel = 1;
  32517. _this._texture = _this._getFromCache(url, true);
  32518. if (!_this._texture) {
  32519. if (!scene.useDelayedTextureLoading) {
  32520. _this.loadTexture();
  32521. }
  32522. else {
  32523. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32524. }
  32525. }
  32526. return _this;
  32527. }
  32528. /**
  32529. * Returns the texture matrix used in most of the material.
  32530. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  32531. */
  32532. ColorGradingTexture.prototype.getTextureMatrix = function () {
  32533. return this._textureMatrix;
  32534. };
  32535. /**
  32536. * Occurs when the file being loaded is a .3dl LUT file.
  32537. */
  32538. ColorGradingTexture.prototype.load3dlTexture = function () {
  32539. var engine = this._engine;
  32540. var texture;
  32541. if (engine.webGLVersion === 1) {
  32542. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32543. }
  32544. else {
  32545. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32546. }
  32547. this._texture = texture;
  32548. var callback = function (text) {
  32549. var data = null;
  32550. var tempData = null;
  32551. var line;
  32552. var lines = text.split('\n');
  32553. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  32554. var maxColor = 0;
  32555. for (var i = 0; i < lines.length; i++) {
  32556. line = lines[i];
  32557. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  32558. continue;
  32559. if (line.indexOf('#') === 0)
  32560. continue;
  32561. var words = line.split(" ");
  32562. if (size === 0) {
  32563. // Number of space + one
  32564. size = words.length;
  32565. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  32566. tempData = new Float32Array(size * size * size * 4);
  32567. continue;
  32568. }
  32569. if (size != 0) {
  32570. var r = Math.max(parseInt(words[0]), 0);
  32571. var g = Math.max(parseInt(words[1]), 0);
  32572. var b = Math.max(parseInt(words[2]), 0);
  32573. maxColor = Math.max(r, maxColor);
  32574. maxColor = Math.max(g, maxColor);
  32575. maxColor = Math.max(b, maxColor);
  32576. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  32577. if (tempData) {
  32578. tempData[pixelStorageIndex + 0] = r;
  32579. tempData[pixelStorageIndex + 1] = g;
  32580. tempData[pixelStorageIndex + 2] = b;
  32581. }
  32582. pixelIndexSlice++;
  32583. if (pixelIndexSlice % size == 0) {
  32584. pixelIndexH++;
  32585. pixelIndexSlice = 0;
  32586. if (pixelIndexH % size == 0) {
  32587. pixelIndexW++;
  32588. pixelIndexH = 0;
  32589. }
  32590. }
  32591. }
  32592. }
  32593. if (tempData && data) {
  32594. for (var i = 0; i < tempData.length; i++) {
  32595. if (i > 0 && (i + 1) % 4 === 0) {
  32596. data[i] = 255;
  32597. }
  32598. else {
  32599. var value = tempData[i];
  32600. data[i] = (value / maxColor * 255);
  32601. }
  32602. }
  32603. }
  32604. if (texture.is3D) {
  32605. texture.updateSize(size, size, size);
  32606. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32607. }
  32608. else {
  32609. texture.updateSize(size * size, size);
  32610. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32611. }
  32612. };
  32613. BABYLON.Tools.LoadFile(this.url, callback);
  32614. return this._texture;
  32615. };
  32616. /**
  32617. * Starts the loading process of the texture.
  32618. */
  32619. ColorGradingTexture.prototype.loadTexture = function () {
  32620. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  32621. this.load3dlTexture();
  32622. }
  32623. };
  32624. /**
  32625. * Clones the color gradind texture.
  32626. */
  32627. ColorGradingTexture.prototype.clone = function () {
  32628. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  32629. // Base texture
  32630. newTexture.level = this.level;
  32631. return newTexture;
  32632. };
  32633. /**
  32634. * Called during delayed load for textures.
  32635. */
  32636. ColorGradingTexture.prototype.delayLoad = function () {
  32637. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32638. return;
  32639. }
  32640. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32641. this._texture = this._getFromCache(this.url, true);
  32642. if (!this._texture) {
  32643. this.loadTexture();
  32644. }
  32645. };
  32646. /**
  32647. * Parses a color grading texture serialized by Babylon.
  32648. * @param parsedTexture The texture information being parsedTexture
  32649. * @param scene The scene to load the texture in
  32650. * @param rootUrl The root url of the data assets to load
  32651. * @return A color gradind texture
  32652. */
  32653. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32654. var texture = null;
  32655. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  32656. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  32657. texture.name = parsedTexture.name;
  32658. texture.level = parsedTexture.level;
  32659. }
  32660. return texture;
  32661. };
  32662. /**
  32663. * Serializes the LUT texture to json format.
  32664. */
  32665. ColorGradingTexture.prototype.serialize = function () {
  32666. if (!this.name) {
  32667. return null;
  32668. }
  32669. var serializationObject = {};
  32670. serializationObject.name = this.name;
  32671. serializationObject.level = this.level;
  32672. serializationObject.customType = "BABYLON.ColorGradingTexture";
  32673. return serializationObject;
  32674. };
  32675. /**
  32676. * Empty line regex stored for GC.
  32677. */
  32678. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  32679. return ColorGradingTexture;
  32680. }(BABYLON.BaseTexture));
  32681. BABYLON.ColorGradingTexture = ColorGradingTexture;
  32682. })(BABYLON || (BABYLON = {}));
  32683. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  32684. var BABYLON;
  32685. (function (BABYLON) {
  32686. /**
  32687. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32688. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32689. * 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;
  32690. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32691. */
  32692. var ColorCurves = /** @class */ (function () {
  32693. function ColorCurves() {
  32694. this._dirty = true;
  32695. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  32696. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  32697. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32698. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  32699. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32700. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  32701. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  32702. this._globalHue = 30;
  32703. this._globalDensity = 0;
  32704. this._globalSaturation = 0;
  32705. this._globalExposure = 0;
  32706. this._highlightsHue = 30;
  32707. this._highlightsDensity = 0;
  32708. this._highlightsSaturation = 0;
  32709. this._highlightsExposure = 0;
  32710. this._midtonesHue = 30;
  32711. this._midtonesDensity = 0;
  32712. this._midtonesSaturation = 0;
  32713. this._midtonesExposure = 0;
  32714. this._shadowsHue = 30;
  32715. this._shadowsDensity = 0;
  32716. this._shadowsSaturation = 0;
  32717. this._shadowsExposure = 0;
  32718. }
  32719. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  32720. /**
  32721. * Gets the global Hue value.
  32722. * 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).
  32723. */
  32724. get: function () {
  32725. return this._globalHue;
  32726. },
  32727. /**
  32728. * Sets the global Hue value.
  32729. * 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).
  32730. */
  32731. set: function (value) {
  32732. this._globalHue = value;
  32733. this._dirty = true;
  32734. },
  32735. enumerable: true,
  32736. configurable: true
  32737. });
  32738. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  32739. /**
  32740. * Gets the global Density value.
  32741. * 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.
  32742. * Values less than zero provide a filter of opposite hue.
  32743. */
  32744. get: function () {
  32745. return this._globalDensity;
  32746. },
  32747. /**
  32748. * Sets the global Density value.
  32749. * 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.
  32750. * Values less than zero provide a filter of opposite hue.
  32751. */
  32752. set: function (value) {
  32753. this._globalDensity = value;
  32754. this._dirty = true;
  32755. },
  32756. enumerable: true,
  32757. configurable: true
  32758. });
  32759. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  32760. /**
  32761. * Gets the global Saturation value.
  32762. * 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.
  32763. */
  32764. get: function () {
  32765. return this._globalSaturation;
  32766. },
  32767. /**
  32768. * Sets the global Saturation value.
  32769. * 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.
  32770. */
  32771. set: function (value) {
  32772. this._globalSaturation = value;
  32773. this._dirty = true;
  32774. },
  32775. enumerable: true,
  32776. configurable: true
  32777. });
  32778. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  32779. /**
  32780. * Gets the highlights Hue value.
  32781. * 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).
  32782. */
  32783. get: function () {
  32784. return this._highlightsHue;
  32785. },
  32786. /**
  32787. * Sets the highlights Hue value.
  32788. * 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).
  32789. */
  32790. set: function (value) {
  32791. this._highlightsHue = value;
  32792. this._dirty = true;
  32793. },
  32794. enumerable: true,
  32795. configurable: true
  32796. });
  32797. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  32798. /**
  32799. * Gets the highlights Density value.
  32800. * 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.
  32801. * Values less than zero provide a filter of opposite hue.
  32802. */
  32803. get: function () {
  32804. return this._highlightsDensity;
  32805. },
  32806. /**
  32807. * Sets the highlights Density value.
  32808. * 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.
  32809. * Values less than zero provide a filter of opposite hue.
  32810. */
  32811. set: function (value) {
  32812. this._highlightsDensity = value;
  32813. this._dirty = true;
  32814. },
  32815. enumerable: true,
  32816. configurable: true
  32817. });
  32818. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  32819. /**
  32820. * Gets the highlights Saturation value.
  32821. * 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.
  32822. */
  32823. get: function () {
  32824. return this._highlightsSaturation;
  32825. },
  32826. /**
  32827. * Sets the highlights Saturation value.
  32828. * 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.
  32829. */
  32830. set: function (value) {
  32831. this._highlightsSaturation = value;
  32832. this._dirty = true;
  32833. },
  32834. enumerable: true,
  32835. configurable: true
  32836. });
  32837. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  32838. /**
  32839. * Gets the highlights Exposure value.
  32840. * 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.
  32841. */
  32842. get: function () {
  32843. return this._highlightsExposure;
  32844. },
  32845. /**
  32846. * Sets the highlights Exposure value.
  32847. * 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.
  32848. */
  32849. set: function (value) {
  32850. this._highlightsExposure = value;
  32851. this._dirty = true;
  32852. },
  32853. enumerable: true,
  32854. configurable: true
  32855. });
  32856. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  32857. /**
  32858. * Gets the midtones Hue value.
  32859. * 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).
  32860. */
  32861. get: function () {
  32862. return this._midtonesHue;
  32863. },
  32864. /**
  32865. * Sets the midtones Hue value.
  32866. * 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).
  32867. */
  32868. set: function (value) {
  32869. this._midtonesHue = value;
  32870. this._dirty = true;
  32871. },
  32872. enumerable: true,
  32873. configurable: true
  32874. });
  32875. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  32876. /**
  32877. * Gets the midtones Density value.
  32878. * 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.
  32879. * Values less than zero provide a filter of opposite hue.
  32880. */
  32881. get: function () {
  32882. return this._midtonesDensity;
  32883. },
  32884. /**
  32885. * Sets the midtones Density value.
  32886. * 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.
  32887. * Values less than zero provide a filter of opposite hue.
  32888. */
  32889. set: function (value) {
  32890. this._midtonesDensity = value;
  32891. this._dirty = true;
  32892. },
  32893. enumerable: true,
  32894. configurable: true
  32895. });
  32896. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  32897. /**
  32898. * Gets the midtones Saturation value.
  32899. * 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.
  32900. */
  32901. get: function () {
  32902. return this._midtonesSaturation;
  32903. },
  32904. /**
  32905. * Sets the midtones Saturation value.
  32906. * 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.
  32907. */
  32908. set: function (value) {
  32909. this._midtonesSaturation = value;
  32910. this._dirty = true;
  32911. },
  32912. enumerable: true,
  32913. configurable: true
  32914. });
  32915. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  32916. /**
  32917. * Gets the midtones Exposure value.
  32918. * 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.
  32919. */
  32920. get: function () {
  32921. return this._midtonesExposure;
  32922. },
  32923. /**
  32924. * Sets the midtones Exposure value.
  32925. * 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.
  32926. */
  32927. set: function (value) {
  32928. this._midtonesExposure = value;
  32929. this._dirty = true;
  32930. },
  32931. enumerable: true,
  32932. configurable: true
  32933. });
  32934. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  32935. /**
  32936. * Gets the shadows Hue value.
  32937. * 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).
  32938. */
  32939. get: function () {
  32940. return this._shadowsHue;
  32941. },
  32942. /**
  32943. * Sets the shadows Hue value.
  32944. * 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).
  32945. */
  32946. set: function (value) {
  32947. this._shadowsHue = value;
  32948. this._dirty = true;
  32949. },
  32950. enumerable: true,
  32951. configurable: true
  32952. });
  32953. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  32954. /**
  32955. * Gets the shadows Density value.
  32956. * 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.
  32957. * Values less than zero provide a filter of opposite hue.
  32958. */
  32959. get: function () {
  32960. return this._shadowsDensity;
  32961. },
  32962. /**
  32963. * Sets the shadows Density value.
  32964. * 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.
  32965. * Values less than zero provide a filter of opposite hue.
  32966. */
  32967. set: function (value) {
  32968. this._shadowsDensity = value;
  32969. this._dirty = true;
  32970. },
  32971. enumerable: true,
  32972. configurable: true
  32973. });
  32974. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  32975. /**
  32976. * Gets the shadows Saturation value.
  32977. * 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.
  32978. */
  32979. get: function () {
  32980. return this._shadowsSaturation;
  32981. },
  32982. /**
  32983. * Sets the shadows Saturation value.
  32984. * 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.
  32985. */
  32986. set: function (value) {
  32987. this._shadowsSaturation = value;
  32988. this._dirty = true;
  32989. },
  32990. enumerable: true,
  32991. configurable: true
  32992. });
  32993. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  32994. /**
  32995. * Gets the shadows Exposure value.
  32996. * 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.
  32997. */
  32998. get: function () {
  32999. return this._shadowsExposure;
  33000. },
  33001. /**
  33002. * Sets the shadows Exposure value.
  33003. * 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.
  33004. */
  33005. set: function (value) {
  33006. this._shadowsExposure = value;
  33007. this._dirty = true;
  33008. },
  33009. enumerable: true,
  33010. configurable: true
  33011. });
  33012. ColorCurves.prototype.getClassName = function () {
  33013. return "ColorCurves";
  33014. };
  33015. /**
  33016. * Binds the color curves to the shader.
  33017. * @param colorCurves The color curve to bind
  33018. * @param effect The effect to bind to
  33019. */
  33020. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33021. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33022. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33023. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33024. if (colorCurves._dirty) {
  33025. colorCurves._dirty = false;
  33026. // Fill in global info.
  33027. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33028. // Compute highlights info.
  33029. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33030. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33031. // Compute midtones info.
  33032. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33033. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33034. // Compute shadows info.
  33035. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33036. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33037. // Compute deltas (neutral is midtones).
  33038. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33039. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33040. }
  33041. if (effect) {
  33042. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33043. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33044. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33045. }
  33046. };
  33047. /**
  33048. * Prepare the list of uniforms associated with the ColorCurves effects.
  33049. * @param uniformsList The list of uniforms used in the effect
  33050. */
  33051. ColorCurves.PrepareUniforms = function (uniformsList) {
  33052. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33053. };
  33054. /**
  33055. * Returns color grading data based on a hue, density, saturation and exposure value.
  33056. * @param filterHue The hue of the color filter.
  33057. * @param filterDensity The density of the color filter.
  33058. * @param saturation The saturation.
  33059. * @param exposure The exposure.
  33060. * @param result The result data container.
  33061. */
  33062. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33063. if (hue == null) {
  33064. return;
  33065. }
  33066. hue = ColorCurves.clamp(hue, 0, 360);
  33067. density = ColorCurves.clamp(density, -100, 100);
  33068. saturation = ColorCurves.clamp(saturation, -100, 100);
  33069. exposure = ColorCurves.clamp(exposure, -100, 100);
  33070. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33071. // so that the maximum filter density is only 50% control. This provides fine control
  33072. // for small values and reasonable range.
  33073. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33074. density *= 0.5;
  33075. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33076. if (density < 0) {
  33077. density *= -1;
  33078. hue = (hue + 180) % 360;
  33079. }
  33080. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33081. result.scaleToRef(2, result);
  33082. result.a = 1 + 0.01 * saturation;
  33083. };
  33084. /**
  33085. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33086. * @param value The input slider value in range [-100,100].
  33087. * @returns Adjusted value.
  33088. */
  33089. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33090. value /= 100;
  33091. var x = Math.abs(value);
  33092. x = Math.pow(x, 2);
  33093. if (value < 0) {
  33094. x *= -1;
  33095. }
  33096. x *= 100;
  33097. return x;
  33098. };
  33099. /**
  33100. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33101. * @param hue The hue (H) input.
  33102. * @param saturation The saturation (S) input.
  33103. * @param brightness The brightness (B) input.
  33104. * @result An RGBA color represented as Vector4.
  33105. */
  33106. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33107. var h = ColorCurves.clamp(hue, 0, 360);
  33108. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33109. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33110. if (s === 0) {
  33111. result.r = v;
  33112. result.g = v;
  33113. result.b = v;
  33114. }
  33115. else {
  33116. // sector 0 to 5
  33117. h /= 60;
  33118. var i = Math.floor(h);
  33119. // fractional part of h
  33120. var f = h - i;
  33121. var p = v * (1 - s);
  33122. var q = v * (1 - s * f);
  33123. var t = v * (1 - s * (1 - f));
  33124. switch (i) {
  33125. case 0:
  33126. result.r = v;
  33127. result.g = t;
  33128. result.b = p;
  33129. break;
  33130. case 1:
  33131. result.r = q;
  33132. result.g = v;
  33133. result.b = p;
  33134. break;
  33135. case 2:
  33136. result.r = p;
  33137. result.g = v;
  33138. result.b = t;
  33139. break;
  33140. case 3:
  33141. result.r = p;
  33142. result.g = q;
  33143. result.b = v;
  33144. break;
  33145. case 4:
  33146. result.r = t;
  33147. result.g = p;
  33148. result.b = v;
  33149. break;
  33150. default:// case 5:
  33151. result.r = v;
  33152. result.g = p;
  33153. result.b = q;
  33154. break;
  33155. }
  33156. }
  33157. result.a = 1;
  33158. };
  33159. /**
  33160. * Returns a value clamped between min and max
  33161. * @param value The value to clamp
  33162. * @param min The minimum of value
  33163. * @param max The maximum of value
  33164. * @returns The clamped value.
  33165. */
  33166. ColorCurves.clamp = function (value, min, max) {
  33167. return Math.min(Math.max(value, min), max);
  33168. };
  33169. /**
  33170. * Clones the current color curve instance.
  33171. * @return The cloned curves
  33172. */
  33173. ColorCurves.prototype.clone = function () {
  33174. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33175. };
  33176. /**
  33177. * Serializes the current color curve instance to a json representation.
  33178. * @return a JSON representation
  33179. */
  33180. ColorCurves.prototype.serialize = function () {
  33181. return BABYLON.SerializationHelper.Serialize(this);
  33182. };
  33183. /**
  33184. * Parses the color curve from a json representation.
  33185. * @param source the JSON source to parse
  33186. * @return The parsed curves
  33187. */
  33188. ColorCurves.Parse = function (source) {
  33189. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33190. };
  33191. __decorate([
  33192. BABYLON.serialize()
  33193. ], ColorCurves.prototype, "_globalHue", void 0);
  33194. __decorate([
  33195. BABYLON.serialize()
  33196. ], ColorCurves.prototype, "_globalDensity", void 0);
  33197. __decorate([
  33198. BABYLON.serialize()
  33199. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33200. __decorate([
  33201. BABYLON.serialize()
  33202. ], ColorCurves.prototype, "_globalExposure", void 0);
  33203. __decorate([
  33204. BABYLON.serialize()
  33205. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33206. __decorate([
  33207. BABYLON.serialize()
  33208. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33209. __decorate([
  33210. BABYLON.serialize()
  33211. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33212. __decorate([
  33213. BABYLON.serialize()
  33214. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33215. __decorate([
  33216. BABYLON.serialize()
  33217. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33218. __decorate([
  33219. BABYLON.serialize()
  33220. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33221. __decorate([
  33222. BABYLON.serialize()
  33223. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33224. __decorate([
  33225. BABYLON.serialize()
  33226. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33227. return ColorCurves;
  33228. }());
  33229. BABYLON.ColorCurves = ColorCurves;
  33230. })(BABYLON || (BABYLON = {}));
  33231. //# sourceMappingURL=babylon.colorCurves.js.map
  33232. var BABYLON;
  33233. (function (BABYLON) {
  33234. var StandardMaterialDefines = /** @class */ (function (_super) {
  33235. __extends(StandardMaterialDefines, _super);
  33236. function StandardMaterialDefines() {
  33237. var _this = _super.call(this) || this;
  33238. _this.MAINUV1 = false;
  33239. _this.MAINUV2 = false;
  33240. _this.DIFFUSE = false;
  33241. _this.DIFFUSEDIRECTUV = 0;
  33242. _this.AMBIENT = false;
  33243. _this.AMBIENTDIRECTUV = 0;
  33244. _this.OPACITY = false;
  33245. _this.OPACITYDIRECTUV = 0;
  33246. _this.OPACITYRGB = false;
  33247. _this.REFLECTION = false;
  33248. _this.EMISSIVE = false;
  33249. _this.EMISSIVEDIRECTUV = 0;
  33250. _this.SPECULAR = false;
  33251. _this.SPECULARDIRECTUV = 0;
  33252. _this.BUMP = false;
  33253. _this.BUMPDIRECTUV = 0;
  33254. _this.PARALLAX = false;
  33255. _this.PARALLAXOCCLUSION = false;
  33256. _this.SPECULAROVERALPHA = false;
  33257. _this.CLIPPLANE = false;
  33258. _this.ALPHATEST = false;
  33259. _this.DEPTHPREPASS = false;
  33260. _this.ALPHAFROMDIFFUSE = false;
  33261. _this.POINTSIZE = false;
  33262. _this.FOG = false;
  33263. _this.SPECULARTERM = false;
  33264. _this.DIFFUSEFRESNEL = false;
  33265. _this.OPACITYFRESNEL = false;
  33266. _this.REFLECTIONFRESNEL = false;
  33267. _this.REFRACTIONFRESNEL = false;
  33268. _this.EMISSIVEFRESNEL = false;
  33269. _this.FRESNEL = false;
  33270. _this.NORMAL = false;
  33271. _this.UV1 = false;
  33272. _this.UV2 = false;
  33273. _this.VERTEXCOLOR = false;
  33274. _this.VERTEXALPHA = false;
  33275. _this.NUM_BONE_INFLUENCERS = 0;
  33276. _this.BonesPerMesh = 0;
  33277. _this.INSTANCES = false;
  33278. _this.GLOSSINESS = false;
  33279. _this.ROUGHNESS = false;
  33280. _this.EMISSIVEASILLUMINATION = false;
  33281. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33282. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33283. _this.LIGHTMAP = false;
  33284. _this.LIGHTMAPDIRECTUV = 0;
  33285. _this.USELIGHTMAPASSHADOWMAP = false;
  33286. _this.REFLECTIONMAP_3D = false;
  33287. _this.REFLECTIONMAP_SPHERICAL = false;
  33288. _this.REFLECTIONMAP_PLANAR = false;
  33289. _this.REFLECTIONMAP_CUBIC = false;
  33290. _this.REFLECTIONMAP_PROJECTION = false;
  33291. _this.REFLECTIONMAP_SKYBOX = false;
  33292. _this.REFLECTIONMAP_EXPLICIT = false;
  33293. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33294. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33295. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33296. _this.INVERTCUBICMAP = false;
  33297. _this.LOGARITHMICDEPTH = false;
  33298. _this.REFRACTION = false;
  33299. _this.REFRACTIONMAP_3D = false;
  33300. _this.REFLECTIONOVERALPHA = false;
  33301. _this.TWOSIDEDLIGHTING = false;
  33302. _this.SHADOWFLOAT = false;
  33303. _this.MORPHTARGETS = false;
  33304. _this.MORPHTARGETS_NORMAL = false;
  33305. _this.MORPHTARGETS_TANGENT = false;
  33306. _this.NUM_MORPH_INFLUENCERS = 0;
  33307. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33308. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33309. _this.IMAGEPROCESSING = false;
  33310. _this.VIGNETTE = false;
  33311. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33312. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33313. _this.TONEMAPPING = false;
  33314. _this.CONTRAST = false;
  33315. _this.COLORCURVES = false;
  33316. _this.COLORGRADING = false;
  33317. _this.COLORGRADING3D = false;
  33318. _this.SAMPLER3DGREENDEPTH = false;
  33319. _this.SAMPLER3DBGRMAP = false;
  33320. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33321. _this.EXPOSURE = false;
  33322. _this.rebuild();
  33323. return _this;
  33324. }
  33325. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33326. var modes = [
  33327. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33328. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33329. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33330. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33331. ];
  33332. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33333. var mode = modes_1[_i];
  33334. this[mode] = (mode === modeToEnable);
  33335. }
  33336. };
  33337. return StandardMaterialDefines;
  33338. }(BABYLON.MaterialDefines));
  33339. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33340. var StandardMaterial = /** @class */ (function (_super) {
  33341. __extends(StandardMaterial, _super);
  33342. function StandardMaterial(name, scene) {
  33343. var _this = _super.call(this, name, scene) || this;
  33344. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33345. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33346. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33347. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33348. _this.specularPower = 64;
  33349. _this._useAlphaFromDiffuseTexture = false;
  33350. _this._useEmissiveAsIllumination = false;
  33351. _this._linkEmissiveWithDiffuse = false;
  33352. _this._useSpecularOverAlpha = false;
  33353. _this._useReflectionOverAlpha = false;
  33354. _this._disableLighting = false;
  33355. _this._useParallax = false;
  33356. _this._useParallaxOcclusion = false;
  33357. _this.parallaxScaleBias = 0.05;
  33358. _this._roughness = 0;
  33359. _this.indexOfRefraction = 0.98;
  33360. _this.invertRefractionY = true;
  33361. _this._useLightmapAsShadowmap = false;
  33362. _this._useReflectionFresnelFromSpecular = false;
  33363. _this._useGlossinessFromSpecularMapAlpha = false;
  33364. _this._maxSimultaneousLights = 4;
  33365. /**
  33366. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33367. */
  33368. _this._invertNormalMapX = false;
  33369. /**
  33370. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33371. */
  33372. _this._invertNormalMapY = false;
  33373. /**
  33374. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33375. */
  33376. _this._twoSidedLighting = false;
  33377. _this._renderTargets = new BABYLON.SmartArray(16);
  33378. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33379. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33380. // Setup the default processing configuration to the scene.
  33381. _this._attachImageProcessingConfiguration(null);
  33382. _this.getRenderTargetTextures = function () {
  33383. _this._renderTargets.reset();
  33384. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33385. _this._renderTargets.push(_this._reflectionTexture);
  33386. }
  33387. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33388. _this._renderTargets.push(_this._refractionTexture);
  33389. }
  33390. return _this._renderTargets;
  33391. };
  33392. return _this;
  33393. }
  33394. ;
  33395. ;
  33396. ;
  33397. ;
  33398. ;
  33399. ;
  33400. ;
  33401. ;
  33402. ;
  33403. ;
  33404. ;
  33405. ;
  33406. ;
  33407. ;
  33408. ;
  33409. ;
  33410. ;
  33411. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  33412. /**
  33413. * Gets the image processing configuration used either in this material.
  33414. */
  33415. get: function () {
  33416. return this._imageProcessingConfiguration;
  33417. },
  33418. /**
  33419. * Sets the Default image processing configuration used either in the this material.
  33420. *
  33421. * If sets to null, the scene one is in use.
  33422. */
  33423. set: function (value) {
  33424. this._attachImageProcessingConfiguration(value);
  33425. // Ensure the effect will be rebuilt.
  33426. this._markAllSubMeshesAsTexturesDirty();
  33427. },
  33428. enumerable: true,
  33429. configurable: true
  33430. });
  33431. /**
  33432. * Attaches a new image processing configuration to the Standard Material.
  33433. * @param configuration
  33434. */
  33435. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33436. var _this = this;
  33437. if (configuration === this._imageProcessingConfiguration) {
  33438. return;
  33439. }
  33440. // Detaches observer.
  33441. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33442. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33443. }
  33444. // Pick the scene configuration if needed.
  33445. if (!configuration) {
  33446. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33447. }
  33448. else {
  33449. this._imageProcessingConfiguration = configuration;
  33450. }
  33451. // Attaches observer.
  33452. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33453. _this._markAllSubMeshesAsImageProcessingDirty();
  33454. });
  33455. };
  33456. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  33457. /**
  33458. * Gets wether the color curves effect is enabled.
  33459. */
  33460. get: function () {
  33461. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33462. },
  33463. /**
  33464. * Sets wether the color curves effect is enabled.
  33465. */
  33466. set: function (value) {
  33467. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33468. },
  33469. enumerable: true,
  33470. configurable: true
  33471. });
  33472. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  33473. /**
  33474. * Gets wether the color grading effect is enabled.
  33475. */
  33476. get: function () {
  33477. return this.imageProcessingConfiguration.colorGradingEnabled;
  33478. },
  33479. /**
  33480. * Gets wether the color grading effect is enabled.
  33481. */
  33482. set: function (value) {
  33483. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33484. },
  33485. enumerable: true,
  33486. configurable: true
  33487. });
  33488. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  33489. /**
  33490. * Gets wether tonemapping is enabled or not.
  33491. */
  33492. get: function () {
  33493. return this._imageProcessingConfiguration.toneMappingEnabled;
  33494. },
  33495. /**
  33496. * Sets wether tonemapping is enabled or not
  33497. */
  33498. set: function (value) {
  33499. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33500. },
  33501. enumerable: true,
  33502. configurable: true
  33503. });
  33504. ;
  33505. ;
  33506. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  33507. /**
  33508. * The camera exposure used on this material.
  33509. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33510. * This corresponds to a photographic exposure.
  33511. */
  33512. get: function () {
  33513. return this._imageProcessingConfiguration.exposure;
  33514. },
  33515. /**
  33516. * The camera exposure used on this material.
  33517. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33518. * This corresponds to a photographic exposure.
  33519. */
  33520. set: function (value) {
  33521. this._imageProcessingConfiguration.exposure = value;
  33522. },
  33523. enumerable: true,
  33524. configurable: true
  33525. });
  33526. ;
  33527. ;
  33528. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  33529. /**
  33530. * Gets The camera contrast used on this material.
  33531. */
  33532. get: function () {
  33533. return this._imageProcessingConfiguration.contrast;
  33534. },
  33535. /**
  33536. * Sets The camera contrast used on this material.
  33537. */
  33538. set: function (value) {
  33539. this._imageProcessingConfiguration.contrast = value;
  33540. },
  33541. enumerable: true,
  33542. configurable: true
  33543. });
  33544. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  33545. /**
  33546. * Gets the Color Grading 2D Lookup Texture.
  33547. */
  33548. get: function () {
  33549. return this._imageProcessingConfiguration.colorGradingTexture;
  33550. },
  33551. /**
  33552. * Sets the Color Grading 2D Lookup Texture.
  33553. */
  33554. set: function (value) {
  33555. this._imageProcessingConfiguration.colorGradingTexture = value;
  33556. },
  33557. enumerable: true,
  33558. configurable: true
  33559. });
  33560. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  33561. /**
  33562. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33563. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33564. * 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;
  33565. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33566. */
  33567. get: function () {
  33568. return this._imageProcessingConfiguration.colorCurves;
  33569. },
  33570. /**
  33571. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33572. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33573. * 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;
  33574. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33575. */
  33576. set: function (value) {
  33577. this._imageProcessingConfiguration.colorCurves = value;
  33578. },
  33579. enumerable: true,
  33580. configurable: true
  33581. });
  33582. StandardMaterial.prototype.getClassName = function () {
  33583. return "StandardMaterial";
  33584. };
  33585. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  33586. get: function () {
  33587. return this._useLogarithmicDepth;
  33588. },
  33589. set: function (value) {
  33590. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33591. this._markAllSubMeshesAsMiscDirty();
  33592. },
  33593. enumerable: true,
  33594. configurable: true
  33595. });
  33596. StandardMaterial.prototype.needAlphaBlending = function () {
  33597. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  33598. };
  33599. StandardMaterial.prototype.needAlphaTesting = function () {
  33600. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  33601. };
  33602. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  33603. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  33604. };
  33605. StandardMaterial.prototype.getAlphaTestTexture = function () {
  33606. return this._diffuseTexture;
  33607. };
  33608. /**
  33609. * Child classes can use it to update shaders
  33610. */
  33611. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33612. if (useInstances === void 0) { useInstances = false; }
  33613. if (subMesh.effect && this.isFrozen) {
  33614. if (this._wasPreviouslyReady && subMesh.effect) {
  33615. return true;
  33616. }
  33617. }
  33618. if (!subMesh._materialDefines) {
  33619. subMesh._materialDefines = new StandardMaterialDefines();
  33620. }
  33621. var scene = this.getScene();
  33622. var defines = subMesh._materialDefines;
  33623. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33624. if (defines._renderId === scene.getRenderId()) {
  33625. return true;
  33626. }
  33627. }
  33628. var engine = scene.getEngine();
  33629. // Lights
  33630. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33631. // Textures
  33632. if (defines._areTexturesDirty) {
  33633. defines._needUVs = false;
  33634. defines.MAINUV1 = false;
  33635. defines.MAINUV2 = false;
  33636. if (scene.texturesEnabled) {
  33637. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33638. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  33639. return false;
  33640. }
  33641. else {
  33642. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  33643. }
  33644. }
  33645. else {
  33646. defines.DIFFUSE = false;
  33647. }
  33648. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33649. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33650. return false;
  33651. }
  33652. else {
  33653. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33654. }
  33655. }
  33656. else {
  33657. defines.AMBIENT = false;
  33658. }
  33659. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33660. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33661. return false;
  33662. }
  33663. else {
  33664. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33665. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33666. }
  33667. }
  33668. else {
  33669. defines.OPACITY = false;
  33670. }
  33671. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33672. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  33673. return false;
  33674. }
  33675. else {
  33676. defines._needNormals = true;
  33677. defines.REFLECTION = true;
  33678. defines.ROUGHNESS = (this._roughness > 0);
  33679. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  33680. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  33681. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  33682. switch (this._reflectionTexture.coordinatesMode) {
  33683. case BABYLON.Texture.CUBIC_MODE:
  33684. case BABYLON.Texture.INVCUBIC_MODE:
  33685. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  33686. break;
  33687. case BABYLON.Texture.EXPLICIT_MODE:
  33688. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  33689. break;
  33690. case BABYLON.Texture.PLANAR_MODE:
  33691. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  33692. break;
  33693. case BABYLON.Texture.PROJECTION_MODE:
  33694. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  33695. break;
  33696. case BABYLON.Texture.SKYBOX_MODE:
  33697. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  33698. break;
  33699. case BABYLON.Texture.SPHERICAL_MODE:
  33700. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  33701. break;
  33702. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33703. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  33704. break;
  33705. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33706. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  33707. break;
  33708. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33709. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  33710. break;
  33711. }
  33712. }
  33713. }
  33714. else {
  33715. defines.REFLECTION = false;
  33716. }
  33717. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33718. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33719. return false;
  33720. }
  33721. else {
  33722. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33723. }
  33724. }
  33725. else {
  33726. defines.EMISSIVE = false;
  33727. }
  33728. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33729. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33730. return false;
  33731. }
  33732. else {
  33733. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33734. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33735. }
  33736. }
  33737. else {
  33738. defines.LIGHTMAP = false;
  33739. }
  33740. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33741. if (!this._specularTexture.isReadyOrNotBlocking()) {
  33742. return false;
  33743. }
  33744. else {
  33745. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  33746. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  33747. }
  33748. }
  33749. else {
  33750. defines.SPECULAR = false;
  33751. }
  33752. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  33753. // Bump texure can not be not blocking.
  33754. if (!this._bumpTexture.isReady()) {
  33755. return false;
  33756. }
  33757. else {
  33758. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33759. defines.PARALLAX = this._useParallax;
  33760. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  33761. }
  33762. }
  33763. else {
  33764. defines.BUMP = false;
  33765. }
  33766. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33767. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  33768. return false;
  33769. }
  33770. else {
  33771. defines._needUVs = true;
  33772. defines.REFRACTION = true;
  33773. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  33774. }
  33775. }
  33776. else {
  33777. defines.REFRACTION = false;
  33778. }
  33779. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  33780. }
  33781. else {
  33782. defines.DIFFUSE = false;
  33783. defines.AMBIENT = false;
  33784. defines.OPACITY = false;
  33785. defines.REFLECTION = false;
  33786. defines.EMISSIVE = false;
  33787. defines.LIGHTMAP = false;
  33788. defines.BUMP = false;
  33789. defines.REFRACTION = false;
  33790. }
  33791. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  33792. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  33793. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  33794. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  33795. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  33796. }
  33797. if (defines._areImageProcessingDirty) {
  33798. if (!this._imageProcessingConfiguration.isReady()) {
  33799. return false;
  33800. }
  33801. this._imageProcessingConfiguration.prepareDefines(defines);
  33802. }
  33803. if (defines._areFresnelDirty) {
  33804. if (StandardMaterial.FresnelEnabled) {
  33805. // Fresnel
  33806. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  33807. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  33808. this._reflectionFresnelParameters) {
  33809. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  33810. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  33811. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  33812. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  33813. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  33814. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  33815. defines._needNormals = true;
  33816. defines.FRESNEL = true;
  33817. }
  33818. }
  33819. else {
  33820. defines.FRESNEL = false;
  33821. }
  33822. }
  33823. // Misc.
  33824. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  33825. // Attribs
  33826. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  33827. // Values that need to be evaluated on every frame
  33828. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  33829. // Get correct effect
  33830. if (defines.isDirty) {
  33831. defines.markAsProcessed();
  33832. scene.resetCachedMaterial();
  33833. // Fallbacks
  33834. var fallbacks = new BABYLON.EffectFallbacks();
  33835. if (defines.REFLECTION) {
  33836. fallbacks.addFallback(0, "REFLECTION");
  33837. }
  33838. if (defines.SPECULAR) {
  33839. fallbacks.addFallback(0, "SPECULAR");
  33840. }
  33841. if (defines.BUMP) {
  33842. fallbacks.addFallback(0, "BUMP");
  33843. }
  33844. if (defines.PARALLAX) {
  33845. fallbacks.addFallback(1, "PARALLAX");
  33846. }
  33847. if (defines.PARALLAXOCCLUSION) {
  33848. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  33849. }
  33850. if (defines.SPECULAROVERALPHA) {
  33851. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  33852. }
  33853. if (defines.FOG) {
  33854. fallbacks.addFallback(1, "FOG");
  33855. }
  33856. if (defines.POINTSIZE) {
  33857. fallbacks.addFallback(0, "POINTSIZE");
  33858. }
  33859. if (defines.LOGARITHMICDEPTH) {
  33860. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  33861. }
  33862. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  33863. if (defines.SPECULARTERM) {
  33864. fallbacks.addFallback(0, "SPECULARTERM");
  33865. }
  33866. if (defines.DIFFUSEFRESNEL) {
  33867. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  33868. }
  33869. if (defines.OPACITYFRESNEL) {
  33870. fallbacks.addFallback(2, "OPACITYFRESNEL");
  33871. }
  33872. if (defines.REFLECTIONFRESNEL) {
  33873. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  33874. }
  33875. if (defines.EMISSIVEFRESNEL) {
  33876. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  33877. }
  33878. if (defines.FRESNEL) {
  33879. fallbacks.addFallback(4, "FRESNEL");
  33880. }
  33881. //Attributes
  33882. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33883. if (defines.NORMAL) {
  33884. attribs.push(BABYLON.VertexBuffer.NormalKind);
  33885. }
  33886. if (defines.UV1) {
  33887. attribs.push(BABYLON.VertexBuffer.UVKind);
  33888. }
  33889. if (defines.UV2) {
  33890. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33891. }
  33892. if (defines.VERTEXCOLOR) {
  33893. attribs.push(BABYLON.VertexBuffer.ColorKind);
  33894. }
  33895. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  33896. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  33897. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  33898. var shaderName = "default";
  33899. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  33900. "vFogInfos", "vFogColor", "pointSize",
  33901. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  33902. "mBones",
  33903. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  33904. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  33905. "logarithmicDepthConstant", "vTangentSpaceParams"
  33906. ];
  33907. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  33908. var uniformBuffers = ["Material", "Scene"];
  33909. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  33910. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  33911. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  33912. uniformsNames: uniforms,
  33913. uniformBuffersNames: uniformBuffers,
  33914. samplers: samplers,
  33915. defines: defines,
  33916. maxSimultaneousLights: this._maxSimultaneousLights
  33917. });
  33918. if (this.customShaderNameResolve) {
  33919. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  33920. }
  33921. var join = defines.toString();
  33922. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  33923. attributes: attribs,
  33924. uniformsNames: uniforms,
  33925. uniformBuffersNames: uniformBuffers,
  33926. samplers: samplers,
  33927. defines: join,
  33928. fallbacks: fallbacks,
  33929. onCompiled: this.onCompiled,
  33930. onError: this.onError,
  33931. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  33932. }, engine), defines);
  33933. this.buildUniformLayout();
  33934. }
  33935. if (!subMesh.effect || !subMesh.effect.isReady()) {
  33936. return false;
  33937. }
  33938. defines._renderId = scene.getRenderId();
  33939. this._wasPreviouslyReady = true;
  33940. return true;
  33941. };
  33942. StandardMaterial.prototype.buildUniformLayout = function () {
  33943. // Order is important !
  33944. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  33945. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  33946. this._uniformBuffer.addUniform("opacityParts", 4);
  33947. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  33948. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  33949. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  33950. this._uniformBuffer.addUniform("refractionRightColor", 4);
  33951. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  33952. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  33953. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  33954. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  33955. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  33956. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  33957. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  33958. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  33959. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  33960. this._uniformBuffer.addUniform("vBumpInfos", 3);
  33961. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  33962. this._uniformBuffer.addUniform("ambientMatrix", 16);
  33963. this._uniformBuffer.addUniform("opacityMatrix", 16);
  33964. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  33965. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  33966. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  33967. this._uniformBuffer.addUniform("specularMatrix", 16);
  33968. this._uniformBuffer.addUniform("bumpMatrix", 16);
  33969. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  33970. this._uniformBuffer.addUniform("refractionMatrix", 16);
  33971. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  33972. this._uniformBuffer.addUniform("vSpecularColor", 4);
  33973. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  33974. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  33975. this._uniformBuffer.addUniform("pointSize", 1);
  33976. this._uniformBuffer.create();
  33977. };
  33978. StandardMaterial.prototype.unbind = function () {
  33979. if (this._activeEffect) {
  33980. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  33981. this._activeEffect.setTexture("reflection2DSampler", null);
  33982. }
  33983. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  33984. this._activeEffect.setTexture("refraction2DSampler", null);
  33985. }
  33986. }
  33987. _super.prototype.unbind.call(this);
  33988. };
  33989. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  33990. var scene = this.getScene();
  33991. var defines = subMesh._materialDefines;
  33992. if (!defines) {
  33993. return;
  33994. }
  33995. var effect = subMesh.effect;
  33996. if (!effect) {
  33997. return;
  33998. }
  33999. this._activeEffect = effect;
  34000. // Matrices
  34001. this.bindOnlyWorldMatrix(world);
  34002. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34003. // Bones
  34004. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  34005. if (mustRebind) {
  34006. this._uniformBuffer.bindToEffect(effect, "Material");
  34007. this.bindViewProjection(effect);
  34008. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34009. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  34010. // Fresnel
  34011. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  34012. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  34013. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  34014. }
  34015. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  34016. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  34017. }
  34018. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  34019. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  34020. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  34021. }
  34022. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  34023. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  34024. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  34025. }
  34026. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  34027. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  34028. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  34029. }
  34030. }
  34031. // Textures
  34032. if (scene.texturesEnabled) {
  34033. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34034. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  34035. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  34036. }
  34037. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34038. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  34039. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34040. }
  34041. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34042. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34043. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34044. }
  34045. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34046. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  34047. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  34048. }
  34049. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34050. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34051. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34052. }
  34053. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34054. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34055. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34056. }
  34057. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34058. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  34059. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  34060. }
  34061. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34062. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  34063. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34064. if (scene._mirroredCameraPosition) {
  34065. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34066. }
  34067. else {
  34068. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34069. }
  34070. }
  34071. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34072. var depth = 1.0;
  34073. if (!this._refractionTexture.isCube) {
  34074. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34075. if (this._refractionTexture.depth) {
  34076. depth = this._refractionTexture.depth;
  34077. }
  34078. }
  34079. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34080. }
  34081. }
  34082. // Point size
  34083. if (this.pointsCloud) {
  34084. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34085. }
  34086. if (defines.SPECULARTERM) {
  34087. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34088. }
  34089. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34090. // Diffuse
  34091. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34092. }
  34093. // Textures
  34094. if (scene.texturesEnabled) {
  34095. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34096. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34097. }
  34098. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34099. effect.setTexture("ambientSampler", this._ambientTexture);
  34100. }
  34101. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34102. effect.setTexture("opacitySampler", this._opacityTexture);
  34103. }
  34104. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34105. if (this._reflectionTexture.isCube) {
  34106. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34107. }
  34108. else {
  34109. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34110. }
  34111. }
  34112. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34113. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34114. }
  34115. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34116. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34117. }
  34118. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34119. effect.setTexture("specularSampler", this._specularTexture);
  34120. }
  34121. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34122. effect.setTexture("bumpSampler", this._bumpTexture);
  34123. }
  34124. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34125. var depth = 1.0;
  34126. if (this._refractionTexture.isCube) {
  34127. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34128. }
  34129. else {
  34130. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34131. }
  34132. }
  34133. }
  34134. // Clip plane
  34135. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34136. // Colors
  34137. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34138. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34139. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34140. }
  34141. if (mustRebind || !this.isFrozen) {
  34142. // Lights
  34143. if (scene.lightsEnabled && !this._disableLighting) {
  34144. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34145. }
  34146. // View
  34147. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34148. this.bindView(effect);
  34149. }
  34150. // Fog
  34151. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34152. // Morph targets
  34153. if (defines.NUM_MORPH_INFLUENCERS) {
  34154. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34155. }
  34156. // Log. depth
  34157. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34158. // image processing
  34159. this._imageProcessingConfiguration.bind(this._activeEffect);
  34160. }
  34161. this._uniformBuffer.update();
  34162. this._afterBind(mesh, this._activeEffect);
  34163. };
  34164. StandardMaterial.prototype.getAnimatables = function () {
  34165. var results = [];
  34166. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34167. results.push(this._diffuseTexture);
  34168. }
  34169. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34170. results.push(this._ambientTexture);
  34171. }
  34172. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34173. results.push(this._opacityTexture);
  34174. }
  34175. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34176. results.push(this._reflectionTexture);
  34177. }
  34178. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34179. results.push(this._emissiveTexture);
  34180. }
  34181. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34182. results.push(this._specularTexture);
  34183. }
  34184. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34185. results.push(this._bumpTexture);
  34186. }
  34187. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34188. results.push(this._lightmapTexture);
  34189. }
  34190. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34191. results.push(this._refractionTexture);
  34192. }
  34193. return results;
  34194. };
  34195. StandardMaterial.prototype.getActiveTextures = function () {
  34196. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34197. if (this._diffuseTexture) {
  34198. activeTextures.push(this._diffuseTexture);
  34199. }
  34200. if (this._ambientTexture) {
  34201. activeTextures.push(this._ambientTexture);
  34202. }
  34203. if (this._opacityTexture) {
  34204. activeTextures.push(this._opacityTexture);
  34205. }
  34206. if (this._reflectionTexture) {
  34207. activeTextures.push(this._reflectionTexture);
  34208. }
  34209. if (this._emissiveTexture) {
  34210. activeTextures.push(this._emissiveTexture);
  34211. }
  34212. if (this._specularTexture) {
  34213. activeTextures.push(this._specularTexture);
  34214. }
  34215. if (this._bumpTexture) {
  34216. activeTextures.push(this._bumpTexture);
  34217. }
  34218. if (this._lightmapTexture) {
  34219. activeTextures.push(this._lightmapTexture);
  34220. }
  34221. if (this._refractionTexture) {
  34222. activeTextures.push(this._refractionTexture);
  34223. }
  34224. return activeTextures;
  34225. };
  34226. StandardMaterial.prototype.hasTexture = function (texture) {
  34227. if (_super.prototype.hasTexture.call(this, texture)) {
  34228. return true;
  34229. }
  34230. if (this._diffuseTexture === texture) {
  34231. return true;
  34232. }
  34233. if (this._ambientTexture === texture) {
  34234. return true;
  34235. }
  34236. if (this._opacityTexture === texture) {
  34237. return true;
  34238. }
  34239. if (this._reflectionTexture === texture) {
  34240. return true;
  34241. }
  34242. if (this._emissiveTexture === texture) {
  34243. return true;
  34244. }
  34245. if (this._specularTexture === texture) {
  34246. return true;
  34247. }
  34248. if (this._bumpTexture === texture) {
  34249. return true;
  34250. }
  34251. if (this._lightmapTexture === texture) {
  34252. return true;
  34253. }
  34254. if (this._refractionTexture === texture) {
  34255. return true;
  34256. }
  34257. return false;
  34258. };
  34259. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34260. if (forceDisposeTextures) {
  34261. if (this._diffuseTexture) {
  34262. this._diffuseTexture.dispose();
  34263. }
  34264. if (this._ambientTexture) {
  34265. this._ambientTexture.dispose();
  34266. }
  34267. if (this._opacityTexture) {
  34268. this._opacityTexture.dispose();
  34269. }
  34270. if (this._reflectionTexture) {
  34271. this._reflectionTexture.dispose();
  34272. }
  34273. if (this._emissiveTexture) {
  34274. this._emissiveTexture.dispose();
  34275. }
  34276. if (this._specularTexture) {
  34277. this._specularTexture.dispose();
  34278. }
  34279. if (this._bumpTexture) {
  34280. this._bumpTexture.dispose();
  34281. }
  34282. if (this._lightmapTexture) {
  34283. this._lightmapTexture.dispose();
  34284. }
  34285. if (this._refractionTexture) {
  34286. this._refractionTexture.dispose();
  34287. }
  34288. }
  34289. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34290. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34291. }
  34292. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34293. };
  34294. StandardMaterial.prototype.clone = function (name) {
  34295. var _this = this;
  34296. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34297. result.name = name;
  34298. result.id = name;
  34299. return result;
  34300. };
  34301. StandardMaterial.prototype.serialize = function () {
  34302. return BABYLON.SerializationHelper.Serialize(this);
  34303. };
  34304. // Statics
  34305. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34306. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34307. };
  34308. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34309. get: function () {
  34310. return StandardMaterial._DiffuseTextureEnabled;
  34311. },
  34312. set: function (value) {
  34313. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34314. return;
  34315. }
  34316. StandardMaterial._DiffuseTextureEnabled = value;
  34317. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34318. },
  34319. enumerable: true,
  34320. configurable: true
  34321. });
  34322. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34323. get: function () {
  34324. return StandardMaterial._AmbientTextureEnabled;
  34325. },
  34326. set: function (value) {
  34327. if (StandardMaterial._AmbientTextureEnabled === value) {
  34328. return;
  34329. }
  34330. StandardMaterial._AmbientTextureEnabled = value;
  34331. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34332. },
  34333. enumerable: true,
  34334. configurable: true
  34335. });
  34336. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34337. get: function () {
  34338. return StandardMaterial._OpacityTextureEnabled;
  34339. },
  34340. set: function (value) {
  34341. if (StandardMaterial._OpacityTextureEnabled === value) {
  34342. return;
  34343. }
  34344. StandardMaterial._OpacityTextureEnabled = value;
  34345. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34346. },
  34347. enumerable: true,
  34348. configurable: true
  34349. });
  34350. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34351. get: function () {
  34352. return StandardMaterial._ReflectionTextureEnabled;
  34353. },
  34354. set: function (value) {
  34355. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34356. return;
  34357. }
  34358. StandardMaterial._ReflectionTextureEnabled = value;
  34359. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34360. },
  34361. enumerable: true,
  34362. configurable: true
  34363. });
  34364. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34365. get: function () {
  34366. return StandardMaterial._EmissiveTextureEnabled;
  34367. },
  34368. set: function (value) {
  34369. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34370. return;
  34371. }
  34372. StandardMaterial._EmissiveTextureEnabled = value;
  34373. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34374. },
  34375. enumerable: true,
  34376. configurable: true
  34377. });
  34378. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34379. get: function () {
  34380. return StandardMaterial._SpecularTextureEnabled;
  34381. },
  34382. set: function (value) {
  34383. if (StandardMaterial._SpecularTextureEnabled === value) {
  34384. return;
  34385. }
  34386. StandardMaterial._SpecularTextureEnabled = value;
  34387. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34388. },
  34389. enumerable: true,
  34390. configurable: true
  34391. });
  34392. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34393. get: function () {
  34394. return StandardMaterial._BumpTextureEnabled;
  34395. },
  34396. set: function (value) {
  34397. if (StandardMaterial._BumpTextureEnabled === value) {
  34398. return;
  34399. }
  34400. StandardMaterial._BumpTextureEnabled = value;
  34401. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34402. },
  34403. enumerable: true,
  34404. configurable: true
  34405. });
  34406. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  34407. get: function () {
  34408. return StandardMaterial._LightmapTextureEnabled;
  34409. },
  34410. set: function (value) {
  34411. if (StandardMaterial._LightmapTextureEnabled === value) {
  34412. return;
  34413. }
  34414. StandardMaterial._LightmapTextureEnabled = value;
  34415. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34416. },
  34417. enumerable: true,
  34418. configurable: true
  34419. });
  34420. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  34421. get: function () {
  34422. return StandardMaterial._RefractionTextureEnabled;
  34423. },
  34424. set: function (value) {
  34425. if (StandardMaterial._RefractionTextureEnabled === value) {
  34426. return;
  34427. }
  34428. StandardMaterial._RefractionTextureEnabled = value;
  34429. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34430. },
  34431. enumerable: true,
  34432. configurable: true
  34433. });
  34434. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  34435. get: function () {
  34436. return StandardMaterial._ColorGradingTextureEnabled;
  34437. },
  34438. set: function (value) {
  34439. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  34440. return;
  34441. }
  34442. StandardMaterial._ColorGradingTextureEnabled = value;
  34443. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34444. },
  34445. enumerable: true,
  34446. configurable: true
  34447. });
  34448. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  34449. get: function () {
  34450. return StandardMaterial._FresnelEnabled;
  34451. },
  34452. set: function (value) {
  34453. if (StandardMaterial._FresnelEnabled === value) {
  34454. return;
  34455. }
  34456. StandardMaterial._FresnelEnabled = value;
  34457. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  34458. },
  34459. enumerable: true,
  34460. configurable: true
  34461. });
  34462. // Flags used to enable or disable a type of texture for all Standard Materials
  34463. StandardMaterial._DiffuseTextureEnabled = true;
  34464. StandardMaterial._AmbientTextureEnabled = true;
  34465. StandardMaterial._OpacityTextureEnabled = true;
  34466. StandardMaterial._ReflectionTextureEnabled = true;
  34467. StandardMaterial._EmissiveTextureEnabled = true;
  34468. StandardMaterial._SpecularTextureEnabled = true;
  34469. StandardMaterial._BumpTextureEnabled = true;
  34470. StandardMaterial._LightmapTextureEnabled = true;
  34471. StandardMaterial._RefractionTextureEnabled = true;
  34472. StandardMaterial._ColorGradingTextureEnabled = true;
  34473. StandardMaterial._FresnelEnabled = true;
  34474. __decorate([
  34475. BABYLON.serializeAsTexture("diffuseTexture")
  34476. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  34477. __decorate([
  34478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34479. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  34480. __decorate([
  34481. BABYLON.serializeAsTexture("ambientTexture")
  34482. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  34483. __decorate([
  34484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34485. ], StandardMaterial.prototype, "ambientTexture", void 0);
  34486. __decorate([
  34487. BABYLON.serializeAsTexture("opacityTexture")
  34488. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  34489. __decorate([
  34490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34491. ], StandardMaterial.prototype, "opacityTexture", void 0);
  34492. __decorate([
  34493. BABYLON.serializeAsTexture("reflectionTexture")
  34494. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  34495. __decorate([
  34496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34497. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  34498. __decorate([
  34499. BABYLON.serializeAsTexture("emissiveTexture")
  34500. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  34501. __decorate([
  34502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34503. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  34504. __decorate([
  34505. BABYLON.serializeAsTexture("specularTexture")
  34506. ], StandardMaterial.prototype, "_specularTexture", void 0);
  34507. __decorate([
  34508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34509. ], StandardMaterial.prototype, "specularTexture", void 0);
  34510. __decorate([
  34511. BABYLON.serializeAsTexture("bumpTexture")
  34512. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  34513. __decorate([
  34514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34515. ], StandardMaterial.prototype, "bumpTexture", void 0);
  34516. __decorate([
  34517. BABYLON.serializeAsTexture("lightmapTexture")
  34518. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  34519. __decorate([
  34520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34521. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  34522. __decorate([
  34523. BABYLON.serializeAsTexture("refractionTexture")
  34524. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  34525. __decorate([
  34526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34527. ], StandardMaterial.prototype, "refractionTexture", void 0);
  34528. __decorate([
  34529. BABYLON.serializeAsColor3("ambient")
  34530. ], StandardMaterial.prototype, "ambientColor", void 0);
  34531. __decorate([
  34532. BABYLON.serializeAsColor3("diffuse")
  34533. ], StandardMaterial.prototype, "diffuseColor", void 0);
  34534. __decorate([
  34535. BABYLON.serializeAsColor3("specular")
  34536. ], StandardMaterial.prototype, "specularColor", void 0);
  34537. __decorate([
  34538. BABYLON.serializeAsColor3("emissive")
  34539. ], StandardMaterial.prototype, "emissiveColor", void 0);
  34540. __decorate([
  34541. BABYLON.serialize()
  34542. ], StandardMaterial.prototype, "specularPower", void 0);
  34543. __decorate([
  34544. BABYLON.serialize("useAlphaFromDiffuseTexture")
  34545. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  34546. __decorate([
  34547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34548. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  34549. __decorate([
  34550. BABYLON.serialize("useEmissiveAsIllumination")
  34551. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  34552. __decorate([
  34553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34554. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  34555. __decorate([
  34556. BABYLON.serialize("linkEmissiveWithDiffuse")
  34557. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  34558. __decorate([
  34559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34560. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  34561. __decorate([
  34562. BABYLON.serialize("useSpecularOverAlpha")
  34563. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  34564. __decorate([
  34565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34566. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  34567. __decorate([
  34568. BABYLON.serialize("useReflectionOverAlpha")
  34569. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  34570. __decorate([
  34571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34572. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  34573. __decorate([
  34574. BABYLON.serialize("disableLighting")
  34575. ], StandardMaterial.prototype, "_disableLighting", void 0);
  34576. __decorate([
  34577. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34578. ], StandardMaterial.prototype, "disableLighting", void 0);
  34579. __decorate([
  34580. BABYLON.serialize("useParallax")
  34581. ], StandardMaterial.prototype, "_useParallax", void 0);
  34582. __decorate([
  34583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34584. ], StandardMaterial.prototype, "useParallax", void 0);
  34585. __decorate([
  34586. BABYLON.serialize("useParallaxOcclusion")
  34587. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  34588. __decorate([
  34589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34590. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  34591. __decorate([
  34592. BABYLON.serialize()
  34593. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  34594. __decorate([
  34595. BABYLON.serialize("roughness")
  34596. ], StandardMaterial.prototype, "_roughness", void 0);
  34597. __decorate([
  34598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34599. ], StandardMaterial.prototype, "roughness", void 0);
  34600. __decorate([
  34601. BABYLON.serialize()
  34602. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  34603. __decorate([
  34604. BABYLON.serialize()
  34605. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  34606. __decorate([
  34607. BABYLON.serialize("useLightmapAsShadowmap")
  34608. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  34609. __decorate([
  34610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34611. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  34612. __decorate([
  34613. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  34614. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  34615. __decorate([
  34616. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34617. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  34618. __decorate([
  34619. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  34620. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  34621. __decorate([
  34622. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34623. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  34624. __decorate([
  34625. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  34626. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  34627. __decorate([
  34628. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34629. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  34630. __decorate([
  34631. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  34632. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  34633. __decorate([
  34634. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34635. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  34636. __decorate([
  34637. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  34638. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  34639. __decorate([
  34640. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34641. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  34642. __decorate([
  34643. BABYLON.serialize("useReflectionFresnelFromSpecular")
  34644. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  34645. __decorate([
  34646. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34647. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  34648. __decorate([
  34649. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  34650. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  34651. __decorate([
  34652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34653. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  34654. __decorate([
  34655. BABYLON.serialize("maxSimultaneousLights")
  34656. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  34657. __decorate([
  34658. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34659. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  34660. __decorate([
  34661. BABYLON.serialize("invertNormalMapX")
  34662. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  34663. __decorate([
  34664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34665. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  34666. __decorate([
  34667. BABYLON.serialize("invertNormalMapY")
  34668. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  34669. __decorate([
  34670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34671. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  34672. __decorate([
  34673. BABYLON.serialize("twoSidedLighting")
  34674. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  34675. __decorate([
  34676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34677. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  34678. __decorate([
  34679. BABYLON.serialize()
  34680. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  34681. return StandardMaterial;
  34682. }(BABYLON.PushMaterial));
  34683. BABYLON.StandardMaterial = StandardMaterial;
  34684. })(BABYLON || (BABYLON = {}));
  34685. //# sourceMappingURL=babylon.standardMaterial.js.map
  34686. var BABYLON;
  34687. (function (BABYLON) {
  34688. var PBRMaterialDefines = /** @class */ (function (_super) {
  34689. __extends(PBRMaterialDefines, _super);
  34690. function PBRMaterialDefines() {
  34691. var _this = _super.call(this) || this;
  34692. _this.PBR = true;
  34693. _this.MAINUV1 = false;
  34694. _this.MAINUV2 = false;
  34695. _this.UV1 = false;
  34696. _this.UV2 = false;
  34697. _this.ALBEDO = false;
  34698. _this.ALBEDODIRECTUV = 0;
  34699. _this.VERTEXCOLOR = false;
  34700. _this.AMBIENT = false;
  34701. _this.AMBIENTDIRECTUV = 0;
  34702. _this.AMBIENTINGRAYSCALE = false;
  34703. _this.OPACITY = false;
  34704. _this.VERTEXALPHA = false;
  34705. _this.OPACITYDIRECTUV = 0;
  34706. _this.OPACITYRGB = false;
  34707. _this.ALPHATEST = false;
  34708. _this.DEPTHPREPASS = false;
  34709. _this.ALPHABLEND = false;
  34710. _this.ALPHAFROMALBEDO = false;
  34711. _this.ALPHATESTVALUE = 0.5;
  34712. _this.SPECULAROVERALPHA = false;
  34713. _this.RADIANCEOVERALPHA = false;
  34714. _this.ALPHAFRESNEL = false;
  34715. _this.PREMULTIPLYALPHA = false;
  34716. _this.EMISSIVE = false;
  34717. _this.EMISSIVEDIRECTUV = 0;
  34718. _this.REFLECTIVITY = false;
  34719. _this.REFLECTIVITYDIRECTUV = 0;
  34720. _this.SPECULARTERM = false;
  34721. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34722. _this.MICROSURFACEAUTOMATIC = false;
  34723. _this.LODBASEDMICROSFURACE = false;
  34724. _this.MICROSURFACEMAP = false;
  34725. _this.MICROSURFACEMAPDIRECTUV = 0;
  34726. _this.METALLICWORKFLOW = false;
  34727. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34728. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34729. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34730. _this.AOSTOREINMETALMAPRED = false;
  34731. _this.ENVIRONMENTBRDF = false;
  34732. _this.NORMAL = false;
  34733. _this.TANGENT = false;
  34734. _this.BUMP = false;
  34735. _this.BUMPDIRECTUV = 0;
  34736. _this.PARALLAX = false;
  34737. _this.PARALLAXOCCLUSION = false;
  34738. _this.NORMALXYSCALE = true;
  34739. _this.LIGHTMAP = false;
  34740. _this.LIGHTMAPDIRECTUV = 0;
  34741. _this.USELIGHTMAPASSHADOWMAP = false;
  34742. _this.REFLECTION = false;
  34743. _this.REFLECTIONMAP_3D = false;
  34744. _this.REFLECTIONMAP_SPHERICAL = false;
  34745. _this.REFLECTIONMAP_PLANAR = false;
  34746. _this.REFLECTIONMAP_CUBIC = false;
  34747. _this.REFLECTIONMAP_PROJECTION = false;
  34748. _this.REFLECTIONMAP_SKYBOX = false;
  34749. _this.REFLECTIONMAP_EXPLICIT = false;
  34750. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34751. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34752. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34753. _this.INVERTCUBICMAP = false;
  34754. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34755. _this.USESPHERICALINVERTEX = false;
  34756. _this.REFLECTIONMAP_OPPOSITEZ = false;
  34757. _this.LODINREFLECTIONALPHA = false;
  34758. _this.GAMMAREFLECTION = false;
  34759. _this.REFRACTION = false;
  34760. _this.REFRACTIONMAP_3D = false;
  34761. _this.REFRACTIONMAP_OPPOSITEZ = false;
  34762. _this.LODINREFRACTIONALPHA = false;
  34763. _this.GAMMAREFRACTION = false;
  34764. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34765. _this.INSTANCES = false;
  34766. _this.NUM_BONE_INFLUENCERS = 0;
  34767. _this.BonesPerMesh = 0;
  34768. _this.NONUNIFORMSCALING = false;
  34769. _this.MORPHTARGETS = false;
  34770. _this.MORPHTARGETS_NORMAL = false;
  34771. _this.MORPHTARGETS_TANGENT = false;
  34772. _this.NUM_MORPH_INFLUENCERS = 0;
  34773. _this.IMAGEPROCESSING = false;
  34774. _this.VIGNETTE = false;
  34775. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34776. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34777. _this.TONEMAPPING = false;
  34778. _this.CONTRAST = false;
  34779. _this.COLORCURVES = false;
  34780. _this.COLORGRADING = false;
  34781. _this.COLORGRADING3D = false;
  34782. _this.SAMPLER3DGREENDEPTH = false;
  34783. _this.SAMPLER3DBGRMAP = false;
  34784. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34785. _this.EXPOSURE = false;
  34786. _this.USEPHYSICALLIGHTFALLOFF = false;
  34787. _this.TWOSIDEDLIGHTING = false;
  34788. _this.SHADOWFLOAT = false;
  34789. _this.CLIPPLANE = false;
  34790. _this.POINTSIZE = false;
  34791. _this.FOG = false;
  34792. _this.LOGARITHMICDEPTH = false;
  34793. _this.FORCENORMALFORWARD = false;
  34794. _this.rebuild();
  34795. return _this;
  34796. }
  34797. PBRMaterialDefines.prototype.reset = function () {
  34798. _super.prototype.reset.call(this);
  34799. this.ALPHATESTVALUE = 0.5;
  34800. this.PBR = true;
  34801. };
  34802. return PBRMaterialDefines;
  34803. }(BABYLON.MaterialDefines));
  34804. /**
  34805. * The Physically based material base class of BJS.
  34806. *
  34807. * This offers the main features of a standard PBR material.
  34808. * For more information, please refer to the documentation :
  34809. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34810. */
  34811. var PBRBaseMaterial = /** @class */ (function (_super) {
  34812. __extends(PBRBaseMaterial, _super);
  34813. /**
  34814. * Instantiates a new PBRMaterial instance.
  34815. *
  34816. * @param name The material name
  34817. * @param scene The scene the material will be use in.
  34818. */
  34819. function PBRBaseMaterial(name, scene) {
  34820. var _this = _super.call(this, name, scene) || this;
  34821. /**
  34822. * Intensity of the direct lights e.g. the four lights available in your scene.
  34823. * This impacts both the direct diffuse and specular highlights.
  34824. */
  34825. _this._directIntensity = 1.0;
  34826. /**
  34827. * Intensity of the emissive part of the material.
  34828. * This helps controlling the emissive effect without modifying the emissive color.
  34829. */
  34830. _this._emissiveIntensity = 1.0;
  34831. /**
  34832. * Intensity of the environment e.g. how much the environment will light the object
  34833. * either through harmonics for rough material or through the refelction for shiny ones.
  34834. */
  34835. _this._environmentIntensity = 1.0;
  34836. /**
  34837. * This is a special control allowing the reduction of the specular highlights coming from the
  34838. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34839. */
  34840. _this._specularIntensity = 1.0;
  34841. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34842. /**
  34843. * Debug Control allowing disabling the bump map on this material.
  34844. */
  34845. _this._disableBumpMap = false;
  34846. /**
  34847. * AKA Occlusion Texture Intensity in other nomenclature.
  34848. */
  34849. _this._ambientTextureStrength = 1.0;
  34850. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34851. /**
  34852. * AKA Diffuse Color in other nomenclature.
  34853. */
  34854. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34855. /**
  34856. * AKA Specular Color in other nomenclature.
  34857. */
  34858. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34859. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  34860. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34861. /**
  34862. * AKA Glossiness in other nomenclature.
  34863. */
  34864. _this._microSurface = 0.9;
  34865. /**
  34866. * source material index of refraction (IOR)' / 'destination material IOR.
  34867. */
  34868. _this._indexOfRefraction = 0.66;
  34869. /**
  34870. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34871. */
  34872. _this._invertRefractionY = false;
  34873. /**
  34874. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34875. * Materials half opaque for instance using refraction could benefit from this control.
  34876. */
  34877. _this._linkRefractionWithTransparency = false;
  34878. _this._useLightmapAsShadowmap = false;
  34879. /**
  34880. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34881. */
  34882. _this._useAlphaFromAlbedoTexture = false;
  34883. /**
  34884. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34885. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34886. */
  34887. _this._useSpecularOverAlpha = true;
  34888. /**
  34889. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34890. */
  34891. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34892. /**
  34893. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34894. */
  34895. _this._useRoughnessFromMetallicTextureAlpha = true;
  34896. /**
  34897. * Specifies if the metallic texture contains the roughness information in its green channel.
  34898. */
  34899. _this._useRoughnessFromMetallicTextureGreen = false;
  34900. /**
  34901. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34902. */
  34903. _this._useMetallnessFromMetallicTextureBlue = false;
  34904. /**
  34905. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34906. */
  34907. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34908. /**
  34909. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34910. */
  34911. _this._useAmbientInGrayScale = false;
  34912. /**
  34913. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34914. * The material will try to infer what glossiness each pixel should be.
  34915. */
  34916. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34917. /**
  34918. * BJS is using an harcoded light falloff based on a manually sets up range.
  34919. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34920. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34921. */
  34922. _this._usePhysicalLightFalloff = true;
  34923. /**
  34924. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34925. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34926. */
  34927. _this._useRadianceOverAlpha = true;
  34928. /**
  34929. * Allows using the bump map in parallax mode.
  34930. */
  34931. _this._useParallax = false;
  34932. /**
  34933. * Allows using the bump map in parallax occlusion mode.
  34934. */
  34935. _this._useParallaxOcclusion = false;
  34936. /**
  34937. * Controls the scale bias of the parallax mode.
  34938. */
  34939. _this._parallaxScaleBias = 0.05;
  34940. /**
  34941. * If sets to true, disables all the lights affecting the material.
  34942. */
  34943. _this._disableLighting = false;
  34944. /**
  34945. * Number of Simultaneous lights allowed on the material.
  34946. */
  34947. _this._maxSimultaneousLights = 4;
  34948. /**
  34949. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  34950. */
  34951. _this._invertNormalMapX = false;
  34952. /**
  34953. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  34954. */
  34955. _this._invertNormalMapY = false;
  34956. /**
  34957. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34958. */
  34959. _this._twoSidedLighting = false;
  34960. /**
  34961. * Defines the alpha limits in alpha test mode.
  34962. */
  34963. _this._alphaCutOff = 0.4;
  34964. /**
  34965. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34966. */
  34967. _this._forceAlphaTest = false;
  34968. /**
  34969. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34970. * And/Or occlude the blended part.
  34971. */
  34972. _this._useAlphaFresnel = false;
  34973. /**
  34974. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  34975. * from cos thetav and roughness:
  34976. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  34977. */
  34978. _this._environmentBRDFTexture = null;
  34979. /**
  34980. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  34981. */
  34982. _this._forceIrradianceInFragment = false;
  34983. /**
  34984. * Force normal to face away from face.
  34985. * (Temporary internal fix to remove before 3.1)
  34986. */
  34987. _this._forceNormalForward = false;
  34988. _this._renderTargets = new BABYLON.SmartArray(16);
  34989. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34990. // Setup the default processing configuration to the scene.
  34991. _this._attachImageProcessingConfiguration(null);
  34992. _this.getRenderTargetTextures = function () {
  34993. _this._renderTargets.reset();
  34994. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34995. _this._renderTargets.push(_this._reflectionTexture);
  34996. }
  34997. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34998. _this._renderTargets.push(_this._refractionTexture);
  34999. }
  35000. return _this._renderTargets;
  35001. };
  35002. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35003. return _this;
  35004. }
  35005. /**
  35006. * Attaches a new image processing configuration to the PBR Material.
  35007. * @param configuration
  35008. */
  35009. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35010. var _this = this;
  35011. if (configuration === this._imageProcessingConfiguration) {
  35012. return;
  35013. }
  35014. // Detaches observer.
  35015. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35016. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35017. }
  35018. // Pick the scene configuration if needed.
  35019. if (!configuration) {
  35020. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35021. }
  35022. else {
  35023. this._imageProcessingConfiguration = configuration;
  35024. }
  35025. // Attaches observer.
  35026. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35027. _this._markAllSubMeshesAsImageProcessingDirty();
  35028. });
  35029. };
  35030. PBRBaseMaterial.prototype.getClassName = function () {
  35031. return "PBRBaseMaterial";
  35032. };
  35033. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35034. get: function () {
  35035. return this._useLogarithmicDepth;
  35036. },
  35037. set: function (value) {
  35038. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35039. },
  35040. enumerable: true,
  35041. configurable: true
  35042. });
  35043. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35044. if (this._linkRefractionWithTransparency) {
  35045. return false;
  35046. }
  35047. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35048. };
  35049. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35050. if (this._forceAlphaTest) {
  35051. return true;
  35052. }
  35053. if (this._linkRefractionWithTransparency) {
  35054. return false;
  35055. }
  35056. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  35057. };
  35058. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35059. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  35060. };
  35061. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35062. return this._albedoTexture;
  35063. };
  35064. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35065. var _this = this;
  35066. if (subMesh.effect && this.isFrozen) {
  35067. if (this._wasPreviouslyReady) {
  35068. return true;
  35069. }
  35070. }
  35071. if (!subMesh._materialDefines) {
  35072. subMesh._materialDefines = new PBRMaterialDefines();
  35073. }
  35074. var scene = this.getScene();
  35075. var defines = subMesh._materialDefines;
  35076. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35077. if (defines._renderId === scene.getRenderId()) {
  35078. return true;
  35079. }
  35080. }
  35081. var engine = scene.getEngine();
  35082. // Lights
  35083. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35084. defines._needNormals = true;
  35085. // Textures
  35086. if (defines._areTexturesDirty) {
  35087. defines._needUVs = false;
  35088. if (scene.texturesEnabled) {
  35089. if (scene.getEngine().getCaps().textureLOD) {
  35090. defines.LODBASEDMICROSFURACE = true;
  35091. }
  35092. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35093. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35094. return false;
  35095. }
  35096. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35097. }
  35098. else {
  35099. defines.ALBEDO = false;
  35100. }
  35101. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35102. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35103. return false;
  35104. }
  35105. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35106. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35107. }
  35108. else {
  35109. defines.AMBIENT = false;
  35110. }
  35111. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35112. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35113. return false;
  35114. }
  35115. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35116. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35117. }
  35118. else {
  35119. defines.OPACITY = false;
  35120. }
  35121. var reflectionTexture = this._getReflectionTexture();
  35122. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35123. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35124. return false;
  35125. }
  35126. defines.REFLECTION = true;
  35127. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35128. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35129. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35130. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35131. defines.INVERTCUBICMAP = true;
  35132. }
  35133. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35134. switch (reflectionTexture.coordinatesMode) {
  35135. case BABYLON.Texture.CUBIC_MODE:
  35136. case BABYLON.Texture.INVCUBIC_MODE:
  35137. defines.REFLECTIONMAP_CUBIC = true;
  35138. break;
  35139. case BABYLON.Texture.EXPLICIT_MODE:
  35140. defines.REFLECTIONMAP_EXPLICIT = true;
  35141. break;
  35142. case BABYLON.Texture.PLANAR_MODE:
  35143. defines.REFLECTIONMAP_PLANAR = true;
  35144. break;
  35145. case BABYLON.Texture.PROJECTION_MODE:
  35146. defines.REFLECTIONMAP_PROJECTION = true;
  35147. break;
  35148. case BABYLON.Texture.SKYBOX_MODE:
  35149. defines.REFLECTIONMAP_SKYBOX = true;
  35150. break;
  35151. case BABYLON.Texture.SPHERICAL_MODE:
  35152. defines.REFLECTIONMAP_SPHERICAL = true;
  35153. break;
  35154. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35155. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35156. break;
  35157. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35158. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35159. break;
  35160. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35161. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35162. break;
  35163. }
  35164. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35165. if (reflectionTexture.sphericalPolynomial) {
  35166. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35167. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35168. defines.USESPHERICALINVERTEX = false;
  35169. }
  35170. else {
  35171. defines.USESPHERICALINVERTEX = true;
  35172. }
  35173. }
  35174. }
  35175. }
  35176. else {
  35177. defines.REFLECTION = false;
  35178. defines.REFLECTIONMAP_3D = false;
  35179. defines.REFLECTIONMAP_SPHERICAL = false;
  35180. defines.REFLECTIONMAP_PLANAR = false;
  35181. defines.REFLECTIONMAP_CUBIC = false;
  35182. defines.REFLECTIONMAP_PROJECTION = false;
  35183. defines.REFLECTIONMAP_SKYBOX = false;
  35184. defines.REFLECTIONMAP_EXPLICIT = false;
  35185. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35186. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35187. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35188. defines.INVERTCUBICMAP = false;
  35189. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35190. defines.USESPHERICALINVERTEX = false;
  35191. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35192. defines.LODINREFLECTIONALPHA = false;
  35193. defines.GAMMAREFLECTION = false;
  35194. }
  35195. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35196. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35197. return false;
  35198. }
  35199. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35200. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35201. }
  35202. else {
  35203. defines.LIGHTMAP = false;
  35204. }
  35205. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35206. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35207. return false;
  35208. }
  35209. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35210. }
  35211. else {
  35212. defines.EMISSIVE = false;
  35213. }
  35214. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35215. if (this._metallicTexture) {
  35216. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35217. return false;
  35218. }
  35219. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35220. defines.METALLICWORKFLOW = true;
  35221. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35222. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35223. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35224. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35225. }
  35226. else if (this._reflectivityTexture) {
  35227. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35228. return false;
  35229. }
  35230. defines.METALLICWORKFLOW = false;
  35231. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35232. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35233. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35234. }
  35235. else {
  35236. defines.METALLICWORKFLOW = false;
  35237. defines.REFLECTIVITY = false;
  35238. }
  35239. if (this._microSurfaceTexture) {
  35240. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35241. return false;
  35242. }
  35243. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35244. }
  35245. else {
  35246. defines.MICROSURFACEMAP = false;
  35247. }
  35248. }
  35249. else {
  35250. defines.REFLECTIVITY = false;
  35251. defines.MICROSURFACEMAP = false;
  35252. }
  35253. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35254. // Bump texure can not be none blocking.
  35255. if (!this._bumpTexture.isReady()) {
  35256. return false;
  35257. }
  35258. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35259. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35260. defines.PARALLAX = true;
  35261. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35262. }
  35263. else {
  35264. defines.PARALLAX = false;
  35265. }
  35266. }
  35267. else {
  35268. defines.BUMP = false;
  35269. }
  35270. var refractionTexture = this._getRefractionTexture();
  35271. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35272. if (!refractionTexture.isReadyOrNotBlocking()) {
  35273. return false;
  35274. }
  35275. defines.REFRACTION = true;
  35276. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35277. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35278. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35279. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35280. if (this._linkRefractionWithTransparency) {
  35281. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35282. }
  35283. }
  35284. else {
  35285. defines.REFRACTION = false;
  35286. }
  35287. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35288. // This is blocking.
  35289. if (!this._environmentBRDFTexture.isReady()) {
  35290. return false;
  35291. }
  35292. defines.ENVIRONMENTBRDF = true;
  35293. }
  35294. else {
  35295. defines.ENVIRONMENTBRDF = false;
  35296. }
  35297. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35298. defines.ALPHAFROMALBEDO = true;
  35299. }
  35300. else {
  35301. defines.ALPHAFROMALBEDO = false;
  35302. }
  35303. }
  35304. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35305. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  35306. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  35307. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35308. defines.METALLICWORKFLOW = true;
  35309. }
  35310. else {
  35311. defines.METALLICWORKFLOW = false;
  35312. }
  35313. if (!this.backFaceCulling && this._twoSidedLighting) {
  35314. defines.TWOSIDEDLIGHTING = true;
  35315. }
  35316. else {
  35317. defines.TWOSIDEDLIGHTING = false;
  35318. }
  35319. defines.ALPHATESTVALUE = this._alphaCutOff;
  35320. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35321. defines.ALPHABLEND = this.needAlphaBlending();
  35322. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35323. }
  35324. if (defines._areImageProcessingDirty) {
  35325. if (!this._imageProcessingConfiguration.isReady()) {
  35326. return false;
  35327. }
  35328. this._imageProcessingConfiguration.prepareDefines(defines);
  35329. }
  35330. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35331. // Misc.
  35332. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35333. // Values that need to be evaluated on every frame
  35334. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35335. // Attribs
  35336. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  35337. if (mesh) {
  35338. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35339. mesh.createNormals(true);
  35340. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35341. }
  35342. }
  35343. }
  35344. // Get correct effect
  35345. if (defines.isDirty) {
  35346. defines.markAsProcessed();
  35347. scene.resetCachedMaterial();
  35348. // Fallbacks
  35349. var fallbacks = new BABYLON.EffectFallbacks();
  35350. var fallbackRank = 0;
  35351. if (defines.USESPHERICALINVERTEX) {
  35352. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  35353. }
  35354. if (defines.FOG) {
  35355. fallbacks.addFallback(fallbackRank, "FOG");
  35356. }
  35357. if (defines.POINTSIZE) {
  35358. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  35359. }
  35360. if (defines.LOGARITHMICDEPTH) {
  35361. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  35362. }
  35363. if (defines.PARALLAX) {
  35364. fallbacks.addFallback(fallbackRank, "PARALLAX");
  35365. }
  35366. if (defines.PARALLAXOCCLUSION) {
  35367. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  35368. }
  35369. if (defines.ENVIRONMENTBRDF) {
  35370. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  35371. }
  35372. if (defines.TANGENT) {
  35373. fallbacks.addFallback(fallbackRank++, "TANGENT");
  35374. }
  35375. if (defines.BUMP) {
  35376. fallbacks.addFallback(fallbackRank++, "BUMP");
  35377. }
  35378. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  35379. if (defines.SPECULARTERM) {
  35380. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  35381. }
  35382. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35383. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  35384. }
  35385. if (defines.LIGHTMAP) {
  35386. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  35387. }
  35388. if (defines.NORMAL) {
  35389. fallbacks.addFallback(fallbackRank++, "NORMAL");
  35390. }
  35391. if (defines.AMBIENT) {
  35392. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  35393. }
  35394. if (defines.EMISSIVE) {
  35395. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  35396. }
  35397. if (defines.VERTEXCOLOR) {
  35398. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  35399. }
  35400. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35401. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  35402. }
  35403. if (defines.MORPHTARGETS) {
  35404. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  35405. }
  35406. //Attributes
  35407. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35408. if (defines.NORMAL) {
  35409. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35410. }
  35411. if (defines.TANGENT) {
  35412. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35413. }
  35414. if (defines.UV1) {
  35415. attribs.push(BABYLON.VertexBuffer.UVKind);
  35416. }
  35417. if (defines.UV2) {
  35418. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35419. }
  35420. if (defines.VERTEXCOLOR) {
  35421. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35422. }
  35423. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35424. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35425. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35426. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35427. "vFogInfos", "vFogColor", "pointSize",
  35428. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35429. "mBones",
  35430. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35431. "vLightingIntensity",
  35432. "logarithmicDepthConstant",
  35433. "vSphericalX", "vSphericalY", "vSphericalZ",
  35434. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35435. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35436. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  35437. "vTangentSpaceParams"
  35438. ];
  35439. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  35440. "bumpSampler", "lightmapSampler", "opacitySampler",
  35441. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  35442. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  35443. "microSurfaceSampler", "environmentBrdfSampler"];
  35444. var uniformBuffers = ["Material", "Scene"];
  35445. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35446. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35447. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35448. uniformsNames: uniforms,
  35449. uniformBuffersNames: uniformBuffers,
  35450. samplers: samplers,
  35451. defines: defines,
  35452. maxSimultaneousLights: this._maxSimultaneousLights
  35453. });
  35454. var onCompiled = function (effect) {
  35455. if (_this.onCompiled) {
  35456. _this.onCompiled(effect);
  35457. }
  35458. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35459. };
  35460. var join = defines.toString();
  35461. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35462. attributes: attribs,
  35463. uniformsNames: uniforms,
  35464. uniformBuffersNames: uniformBuffers,
  35465. samplers: samplers,
  35466. defines: join,
  35467. fallbacks: fallbacks,
  35468. onCompiled: onCompiled,
  35469. onError: this.onError,
  35470. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35471. }, engine), defines);
  35472. this.buildUniformLayout();
  35473. }
  35474. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35475. return false;
  35476. }
  35477. defines._renderId = scene.getRenderId();
  35478. this._wasPreviouslyReady = true;
  35479. return true;
  35480. };
  35481. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35482. // Order is important !
  35483. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35484. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35485. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35486. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35487. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35488. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35489. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35490. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35491. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35492. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35493. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35494. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35495. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35496. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35497. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35498. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35499. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35500. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35501. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35502. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35503. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35504. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35505. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35506. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35507. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  35508. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  35509. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35510. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35511. this._uniformBuffer.addUniform("pointSize", 1);
  35512. this._uniformBuffer.create();
  35513. };
  35514. PBRBaseMaterial.prototype.unbind = function () {
  35515. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35516. this._uniformBuffer.setTexture("reflectionSampler", null);
  35517. }
  35518. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35519. this._uniformBuffer.setTexture("refractionSampler", null);
  35520. }
  35521. _super.prototype.unbind.call(this);
  35522. };
  35523. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35524. this._activeEffect.setMatrix("world", world);
  35525. };
  35526. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35527. var scene = this.getScene();
  35528. var defines = subMesh._materialDefines;
  35529. if (!defines) {
  35530. return;
  35531. }
  35532. var effect = subMesh.effect;
  35533. if (!effect) {
  35534. return;
  35535. }
  35536. this._activeEffect = effect;
  35537. // Matrices
  35538. this.bindOnlyWorldMatrix(world);
  35539. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35540. // Bones
  35541. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35542. var reflectionTexture = null;
  35543. if (mustRebind) {
  35544. this._uniformBuffer.bindToEffect(effect, "Material");
  35545. this.bindViewProjection(effect);
  35546. reflectionTexture = this._getReflectionTexture();
  35547. var refractionTexture = this._getRefractionTexture();
  35548. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35549. // Texture uniforms
  35550. if (scene.texturesEnabled) {
  35551. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35552. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35553. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  35554. }
  35555. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35556. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35557. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35558. }
  35559. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35560. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35561. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35562. }
  35563. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35564. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35565. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35566. var polynomials = reflectionTexture.sphericalPolynomial;
  35567. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  35568. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  35569. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  35570. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  35571. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  35572. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  35573. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  35574. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  35575. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  35576. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  35577. }
  35578. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  35579. }
  35580. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35581. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35582. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35583. }
  35584. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35585. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35586. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35587. }
  35588. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35589. if (this._metallicTexture) {
  35590. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35591. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  35592. }
  35593. else if (this._reflectivityTexture) {
  35594. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35595. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  35596. }
  35597. if (this._microSurfaceTexture) {
  35598. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35599. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  35600. }
  35601. }
  35602. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35603. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35604. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35605. if (scene._mirroredCameraPosition) {
  35606. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35607. }
  35608. else {
  35609. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35610. }
  35611. }
  35612. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35613. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  35614. var depth = 1.0;
  35615. if (!refractionTexture.isCube) {
  35616. if (refractionTexture.depth) {
  35617. depth = refractionTexture.depth;
  35618. }
  35619. }
  35620. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35621. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  35622. }
  35623. }
  35624. // Point size
  35625. if (this.pointsCloud) {
  35626. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35627. }
  35628. // Colors
  35629. if (defines.METALLICWORKFLOW) {
  35630. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35631. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35632. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35633. }
  35634. else {
  35635. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35636. }
  35637. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35638. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35639. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35640. // Misc
  35641. this._lightingInfos.x = this._directIntensity;
  35642. this._lightingInfos.y = this._emissiveIntensity;
  35643. this._lightingInfos.z = this._environmentIntensity;
  35644. this._lightingInfos.w = this._specularIntensity;
  35645. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35646. }
  35647. // Textures
  35648. if (scene.texturesEnabled) {
  35649. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35650. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35651. }
  35652. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35653. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35654. }
  35655. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35656. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35657. }
  35658. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35659. if (defines.LODBASEDMICROSFURACE) {
  35660. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  35661. }
  35662. else {
  35663. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  35664. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  35665. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  35666. }
  35667. }
  35668. if (defines.ENVIRONMENTBRDF) {
  35669. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  35670. }
  35671. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35672. if (defines.LODBASEDMICROSFURACE) {
  35673. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  35674. }
  35675. else {
  35676. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  35677. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  35678. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  35679. }
  35680. }
  35681. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35682. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35683. }
  35684. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35685. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35686. }
  35687. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35688. if (this._metallicTexture) {
  35689. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35690. }
  35691. else if (this._reflectivityTexture) {
  35692. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35693. }
  35694. if (this._microSurfaceTexture) {
  35695. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35696. }
  35697. }
  35698. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35699. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35700. }
  35701. }
  35702. // Clip plane
  35703. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35704. // Colors
  35705. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35706. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35707. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  35708. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  35709. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35710. }
  35711. if (mustRebind || !this.isFrozen) {
  35712. // Lights
  35713. if (scene.lightsEnabled && !this._disableLighting) {
  35714. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35715. }
  35716. // View
  35717. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35718. this.bindView(effect);
  35719. }
  35720. // Fog
  35721. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35722. // Morph targets
  35723. if (defines.NUM_MORPH_INFLUENCERS) {
  35724. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35725. }
  35726. // image processing
  35727. this._imageProcessingConfiguration.bind(this._activeEffect);
  35728. // Log. depth
  35729. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35730. }
  35731. this._uniformBuffer.update();
  35732. this._afterBind(mesh);
  35733. };
  35734. PBRBaseMaterial.prototype.getAnimatables = function () {
  35735. var results = [];
  35736. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35737. results.push(this._albedoTexture);
  35738. }
  35739. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35740. results.push(this._ambientTexture);
  35741. }
  35742. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35743. results.push(this._opacityTexture);
  35744. }
  35745. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35746. results.push(this._reflectionTexture);
  35747. }
  35748. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35749. results.push(this._emissiveTexture);
  35750. }
  35751. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35752. results.push(this._metallicTexture);
  35753. }
  35754. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35755. results.push(this._reflectivityTexture);
  35756. }
  35757. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35758. results.push(this._bumpTexture);
  35759. }
  35760. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35761. results.push(this._lightmapTexture);
  35762. }
  35763. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35764. results.push(this._refractionTexture);
  35765. }
  35766. return results;
  35767. };
  35768. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  35769. if (this._reflectionTexture) {
  35770. return this._reflectionTexture;
  35771. }
  35772. return this.getScene().environmentTexture;
  35773. };
  35774. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  35775. if (this._refractionTexture) {
  35776. return this._refractionTexture;
  35777. }
  35778. if (this._linkRefractionWithTransparency) {
  35779. return this.getScene().environmentTexture;
  35780. }
  35781. return null;
  35782. };
  35783. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35784. if (forceDisposeTextures) {
  35785. if (this._albedoTexture) {
  35786. this._albedoTexture.dispose();
  35787. }
  35788. if (this._ambientTexture) {
  35789. this._ambientTexture.dispose();
  35790. }
  35791. if (this._opacityTexture) {
  35792. this._opacityTexture.dispose();
  35793. }
  35794. if (this._reflectionTexture) {
  35795. this._reflectionTexture.dispose();
  35796. }
  35797. if (this._environmentBRDFTexture) {
  35798. this._environmentBRDFTexture.dispose();
  35799. }
  35800. if (this._emissiveTexture) {
  35801. this._emissiveTexture.dispose();
  35802. }
  35803. if (this._metallicTexture) {
  35804. this._metallicTexture.dispose();
  35805. }
  35806. if (this._reflectivityTexture) {
  35807. this._reflectivityTexture.dispose();
  35808. }
  35809. if (this._bumpTexture) {
  35810. this._bumpTexture.dispose();
  35811. }
  35812. if (this._lightmapTexture) {
  35813. this._lightmapTexture.dispose();
  35814. }
  35815. if (this._refractionTexture) {
  35816. this._refractionTexture.dispose();
  35817. }
  35818. }
  35819. this._renderTargets.dispose();
  35820. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35821. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35822. }
  35823. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35824. };
  35825. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35826. __decorate([
  35827. BABYLON.serializeAsImageProcessingConfiguration()
  35828. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35829. __decorate([
  35830. BABYLON.serialize()
  35831. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35832. return PBRBaseMaterial;
  35833. }(BABYLON.PushMaterial));
  35834. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35835. })(BABYLON || (BABYLON = {}));
  35836. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35837. var BABYLON;
  35838. (function (BABYLON) {
  35839. var Internals;
  35840. (function (Internals) {
  35841. /**
  35842. * The Physically based simple base material of BJS.
  35843. *
  35844. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35845. * It is used as the base class for both the specGloss and metalRough conventions.
  35846. */
  35847. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  35848. __extends(PBRBaseSimpleMaterial, _super);
  35849. /**
  35850. * Instantiates a new PBRMaterial instance.
  35851. *
  35852. * @param name The material name
  35853. * @param scene The scene the material will be use in.
  35854. */
  35855. function PBRBaseSimpleMaterial(name, scene) {
  35856. var _this = _super.call(this, name, scene) || this;
  35857. /**
  35858. * Number of Simultaneous lights allowed on the material.
  35859. */
  35860. _this.maxSimultaneousLights = 4;
  35861. /**
  35862. * If sets to true, disables all the lights affecting the material.
  35863. */
  35864. _this.disableLighting = false;
  35865. /**
  35866. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35867. */
  35868. _this.invertNormalMapX = false;
  35869. /**
  35870. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35871. */
  35872. _this.invertNormalMapY = false;
  35873. /**
  35874. * Emissivie color used to self-illuminate the model.
  35875. */
  35876. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35877. /**
  35878. * Occlusion Channel Strenght.
  35879. */
  35880. _this.occlusionStrength = 1.0;
  35881. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35882. _this._useAmbientInGrayScale = true;
  35883. return _this;
  35884. }
  35885. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35886. /**
  35887. * Gets the current transparency mode.
  35888. */
  35889. get: function () {
  35890. return this._transparencyMode;
  35891. },
  35892. /**
  35893. * Sets the transparency mode of the material.
  35894. */
  35895. set: function (value) {
  35896. if (this._transparencyMode === value) {
  35897. return;
  35898. }
  35899. this._transparencyMode = value;
  35900. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35901. this._forceAlphaTest = true;
  35902. }
  35903. else {
  35904. this._forceAlphaTest = false;
  35905. }
  35906. this._markAllSubMeshesAsTexturesDirty();
  35907. },
  35908. enumerable: true,
  35909. configurable: true
  35910. });
  35911. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35912. /**
  35913. * Gets the current double sided mode.
  35914. */
  35915. get: function () {
  35916. return this._twoSidedLighting;
  35917. },
  35918. /**
  35919. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35920. */
  35921. set: function (value) {
  35922. if (this._twoSidedLighting === value) {
  35923. return;
  35924. }
  35925. this._twoSidedLighting = value;
  35926. this.backFaceCulling = !value;
  35927. this._markAllSubMeshesAsTexturesDirty();
  35928. },
  35929. enumerable: true,
  35930. configurable: true
  35931. });
  35932. /**
  35933. * Specifies wether or not the alpha value of the albedo texture should be used.
  35934. */
  35935. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35936. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35937. };
  35938. /**
  35939. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35940. */
  35941. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35942. if (this._linkRefractionWithTransparency) {
  35943. return false;
  35944. }
  35945. return (this.alpha < 1.0) ||
  35946. (this._shouldUseAlphaFromAlbedoTexture() &&
  35947. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35948. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35949. };
  35950. /**
  35951. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35952. */
  35953. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35954. if (this._linkRefractionWithTransparency) {
  35955. return false;
  35956. }
  35957. return this._shouldUseAlphaFromAlbedoTexture() &&
  35958. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35959. };
  35960. /**
  35961. * Return the active textures of the material.
  35962. */
  35963. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  35964. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35965. if (this.environmentTexture) {
  35966. activeTextures.push(this.environmentTexture);
  35967. }
  35968. if (this.normalTexture) {
  35969. activeTextures.push(this.normalTexture);
  35970. }
  35971. if (this.emissiveTexture) {
  35972. activeTextures.push(this.emissiveTexture);
  35973. }
  35974. if (this.occlusionTexture) {
  35975. activeTextures.push(this.occlusionTexture);
  35976. }
  35977. return activeTextures;
  35978. };
  35979. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  35980. return "PBRBaseSimpleMaterial";
  35981. };
  35982. __decorate([
  35983. BABYLON.serialize(),
  35984. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35985. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  35986. __decorate([
  35987. BABYLON.serialize(),
  35988. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35989. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  35990. __decorate([
  35991. BABYLON.serializeAsTexture(),
  35992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  35993. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  35994. __decorate([
  35995. BABYLON.serialize(),
  35996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35997. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  35998. __decorate([
  35999. BABYLON.serialize(),
  36000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36001. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36002. __decorate([
  36003. BABYLON.serializeAsTexture(),
  36004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36005. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36006. __decorate([
  36007. BABYLON.serializeAsColor3("emissive"),
  36008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36009. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36010. __decorate([
  36011. BABYLON.serializeAsTexture(),
  36012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36013. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36014. __decorate([
  36015. BABYLON.serialize(),
  36016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36017. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36018. __decorate([
  36019. BABYLON.serializeAsTexture(),
  36020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36021. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36022. __decorate([
  36023. BABYLON.serialize(),
  36024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36025. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36026. __decorate([
  36027. BABYLON.serialize()
  36028. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  36029. __decorate([
  36030. BABYLON.serialize()
  36031. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36032. return PBRBaseSimpleMaterial;
  36033. }(BABYLON.PBRBaseMaterial));
  36034. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36035. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36036. })(BABYLON || (BABYLON = {}));
  36037. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36038. var BABYLON;
  36039. (function (BABYLON) {
  36040. /**
  36041. * The Physically based material of BJS.
  36042. *
  36043. * This offers the main features of a standard PBR material.
  36044. * For more information, please refer to the documentation :
  36045. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36046. */
  36047. var PBRMaterial = /** @class */ (function (_super) {
  36048. __extends(PBRMaterial, _super);
  36049. /**
  36050. * Instantiates a new PBRMaterial instance.
  36051. *
  36052. * @param name The material name
  36053. * @param scene The scene the material will be use in.
  36054. */
  36055. function PBRMaterial(name, scene) {
  36056. var _this = _super.call(this, name, scene) || this;
  36057. /**
  36058. * Intensity of the direct lights e.g. the four lights available in your scene.
  36059. * This impacts both the direct diffuse and specular highlights.
  36060. */
  36061. _this.directIntensity = 1.0;
  36062. /**
  36063. * Intensity of the emissive part of the material.
  36064. * This helps controlling the emissive effect without modifying the emissive color.
  36065. */
  36066. _this.emissiveIntensity = 1.0;
  36067. /**
  36068. * Intensity of the environment e.g. how much the environment will light the object
  36069. * either through harmonics for rough material or through the refelction for shiny ones.
  36070. */
  36071. _this.environmentIntensity = 1.0;
  36072. /**
  36073. * This is a special control allowing the reduction of the specular highlights coming from the
  36074. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36075. */
  36076. _this.specularIntensity = 1.0;
  36077. /**
  36078. * Debug Control allowing disabling the bump map on this material.
  36079. */
  36080. _this.disableBumpMap = false;
  36081. /**
  36082. * AKA Occlusion Texture Intensity in other nomenclature.
  36083. */
  36084. _this.ambientTextureStrength = 1.0;
  36085. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36086. /**
  36087. * AKA Diffuse Color in other nomenclature.
  36088. */
  36089. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36090. /**
  36091. * AKA Specular Color in other nomenclature.
  36092. */
  36093. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36094. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36095. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36096. /**
  36097. * AKA Glossiness in other nomenclature.
  36098. */
  36099. _this.microSurface = 1.0;
  36100. /**
  36101. * source material index of refraction (IOR)' / 'destination material IOR.
  36102. */
  36103. _this.indexOfRefraction = 0.66;
  36104. /**
  36105. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36106. */
  36107. _this.invertRefractionY = false;
  36108. /**
  36109. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36110. * Materials half opaque for instance using refraction could benefit from this control.
  36111. */
  36112. _this.linkRefractionWithTransparency = false;
  36113. _this.useLightmapAsShadowmap = false;
  36114. /**
  36115. * Specifies that the alpha is coming form the albedo channel alpha channel.
  36116. */
  36117. _this.useAlphaFromAlbedoTexture = false;
  36118. /**
  36119. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36120. */
  36121. _this.forceAlphaTest = false;
  36122. /**
  36123. * Defines the alpha limits in alpha test mode.
  36124. */
  36125. _this.alphaCutOff = 0.4;
  36126. /**
  36127. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36128. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36129. */
  36130. _this.useSpecularOverAlpha = true;
  36131. /**
  36132. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36133. */
  36134. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36135. /**
  36136. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36137. */
  36138. _this.useRoughnessFromMetallicTextureAlpha = true;
  36139. /**
  36140. * Specifies if the metallic texture contains the roughness information in its green channel.
  36141. */
  36142. _this.useRoughnessFromMetallicTextureGreen = false;
  36143. /**
  36144. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36145. */
  36146. _this.useMetallnessFromMetallicTextureBlue = false;
  36147. /**
  36148. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36149. */
  36150. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36151. /**
  36152. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36153. */
  36154. _this.useAmbientInGrayScale = false;
  36155. /**
  36156. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36157. * The material will try to infer what glossiness each pixel should be.
  36158. */
  36159. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36160. /**
  36161. * BJS is using an harcoded light falloff based on a manually sets up range.
  36162. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36163. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36164. */
  36165. _this.usePhysicalLightFalloff = true;
  36166. /**
  36167. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36168. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36169. */
  36170. _this.useRadianceOverAlpha = true;
  36171. /**
  36172. * Allows using the bump map in parallax mode.
  36173. */
  36174. _this.useParallax = false;
  36175. /**
  36176. * Allows using the bump map in parallax occlusion mode.
  36177. */
  36178. _this.useParallaxOcclusion = false;
  36179. /**
  36180. * Controls the scale bias of the parallax mode.
  36181. */
  36182. _this.parallaxScaleBias = 0.05;
  36183. /**
  36184. * If sets to true, disables all the lights affecting the material.
  36185. */
  36186. _this.disableLighting = false;
  36187. /**
  36188. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36189. */
  36190. _this.forceIrradianceInFragment = false;
  36191. /**
  36192. * Number of Simultaneous lights allowed on the material.
  36193. */
  36194. _this.maxSimultaneousLights = 4;
  36195. /**
  36196. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36197. */
  36198. _this.invertNormalMapX = false;
  36199. /**
  36200. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36201. */
  36202. _this.invertNormalMapY = false;
  36203. /**
  36204. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36205. */
  36206. _this.twoSidedLighting = false;
  36207. /**
  36208. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36209. * And/Or occlude the blended part.
  36210. */
  36211. _this.useAlphaFresnel = false;
  36212. /**
  36213. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36214. * And/Or occlude the blended part.
  36215. */
  36216. _this.environmentBRDFTexture = null;
  36217. /**
  36218. * Force normal to face away from face.
  36219. * (Temporary internal fix to remove before 3.1)
  36220. */
  36221. _this.forceNormalForward = false;
  36222. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36223. return _this;
  36224. }
  36225. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36226. /**
  36227. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36228. */
  36229. get: function () {
  36230. return this._PBRMATERIAL_OPAQUE;
  36231. },
  36232. enumerable: true,
  36233. configurable: true
  36234. });
  36235. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36236. /**
  36237. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36238. */
  36239. get: function () {
  36240. return this._PBRMATERIAL_ALPHATEST;
  36241. },
  36242. enumerable: true,
  36243. configurable: true
  36244. });
  36245. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36246. /**
  36247. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36248. */
  36249. get: function () {
  36250. return this._PBRMATERIAL_ALPHABLEND;
  36251. },
  36252. enumerable: true,
  36253. configurable: true
  36254. });
  36255. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36256. /**
  36257. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36258. * They are also discarded below the alpha cutoff threshold to improve performances.
  36259. */
  36260. get: function () {
  36261. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36262. },
  36263. enumerable: true,
  36264. configurable: true
  36265. });
  36266. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36267. /**
  36268. * Gets the image processing configuration used either in this material.
  36269. */
  36270. get: function () {
  36271. return this._imageProcessingConfiguration;
  36272. },
  36273. /**
  36274. * Sets the Default image processing configuration used either in the this material.
  36275. *
  36276. * If sets to null, the scene one is in use.
  36277. */
  36278. set: function (value) {
  36279. this._attachImageProcessingConfiguration(value);
  36280. // Ensure the effect will be rebuilt.
  36281. this._markAllSubMeshesAsTexturesDirty();
  36282. },
  36283. enumerable: true,
  36284. configurable: true
  36285. });
  36286. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36287. /**
  36288. * Gets wether the color curves effect is enabled.
  36289. */
  36290. get: function () {
  36291. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36292. },
  36293. /**
  36294. * Sets wether the color curves effect is enabled.
  36295. */
  36296. set: function (value) {
  36297. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36298. },
  36299. enumerable: true,
  36300. configurable: true
  36301. });
  36302. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36303. /**
  36304. * Gets wether the color grading effect is enabled.
  36305. */
  36306. get: function () {
  36307. return this.imageProcessingConfiguration.colorGradingEnabled;
  36308. },
  36309. /**
  36310. * Gets wether the color grading effect is enabled.
  36311. */
  36312. set: function (value) {
  36313. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36314. },
  36315. enumerable: true,
  36316. configurable: true
  36317. });
  36318. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36319. /**
  36320. * Gets wether tonemapping is enabled or not.
  36321. */
  36322. get: function () {
  36323. return this._imageProcessingConfiguration.toneMappingEnabled;
  36324. },
  36325. /**
  36326. * Sets wether tonemapping is enabled or not
  36327. */
  36328. set: function (value) {
  36329. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36330. },
  36331. enumerable: true,
  36332. configurable: true
  36333. });
  36334. ;
  36335. ;
  36336. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36337. /**
  36338. * The camera exposure used on this material.
  36339. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36340. * This corresponds to a photographic exposure.
  36341. */
  36342. get: function () {
  36343. return this._imageProcessingConfiguration.exposure;
  36344. },
  36345. /**
  36346. * The camera exposure used on this material.
  36347. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36348. * This corresponds to a photographic exposure.
  36349. */
  36350. set: function (value) {
  36351. this._imageProcessingConfiguration.exposure = value;
  36352. },
  36353. enumerable: true,
  36354. configurable: true
  36355. });
  36356. ;
  36357. ;
  36358. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36359. /**
  36360. * Gets The camera contrast used on this material.
  36361. */
  36362. get: function () {
  36363. return this._imageProcessingConfiguration.contrast;
  36364. },
  36365. /**
  36366. * Sets The camera contrast used on this material.
  36367. */
  36368. set: function (value) {
  36369. this._imageProcessingConfiguration.contrast = value;
  36370. },
  36371. enumerable: true,
  36372. configurable: true
  36373. });
  36374. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36375. /**
  36376. * Gets the Color Grading 2D Lookup Texture.
  36377. */
  36378. get: function () {
  36379. return this._imageProcessingConfiguration.colorGradingTexture;
  36380. },
  36381. /**
  36382. * Sets the Color Grading 2D Lookup Texture.
  36383. */
  36384. set: function (value) {
  36385. this._imageProcessingConfiguration.colorGradingTexture = value;
  36386. },
  36387. enumerable: true,
  36388. configurable: true
  36389. });
  36390. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36391. /**
  36392. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36393. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36394. * 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;
  36395. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36396. */
  36397. get: function () {
  36398. return this._imageProcessingConfiguration.colorCurves;
  36399. },
  36400. /**
  36401. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36402. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36403. * 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;
  36404. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36405. */
  36406. set: function (value) {
  36407. this._imageProcessingConfiguration.colorCurves = value;
  36408. },
  36409. enumerable: true,
  36410. configurable: true
  36411. });
  36412. PBRMaterial.prototype.getClassName = function () {
  36413. return "PBRMaterial";
  36414. };
  36415. PBRMaterial.prototype.getActiveTextures = function () {
  36416. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36417. if (this._albedoTexture) {
  36418. activeTextures.push(this._albedoTexture);
  36419. }
  36420. if (this._ambientTexture) {
  36421. activeTextures.push(this._ambientTexture);
  36422. }
  36423. if (this._opacityTexture) {
  36424. activeTextures.push(this._opacityTexture);
  36425. }
  36426. if (this._reflectionTexture) {
  36427. activeTextures.push(this._reflectionTexture);
  36428. }
  36429. if (this._emissiveTexture) {
  36430. activeTextures.push(this._emissiveTexture);
  36431. }
  36432. if (this._reflectivityTexture) {
  36433. activeTextures.push(this._reflectivityTexture);
  36434. }
  36435. if (this._metallicTexture) {
  36436. activeTextures.push(this._metallicTexture);
  36437. }
  36438. if (this._microSurfaceTexture) {
  36439. activeTextures.push(this._microSurfaceTexture);
  36440. }
  36441. if (this._bumpTexture) {
  36442. activeTextures.push(this._bumpTexture);
  36443. }
  36444. if (this._lightmapTexture) {
  36445. activeTextures.push(this._lightmapTexture);
  36446. }
  36447. if (this._refractionTexture) {
  36448. activeTextures.push(this._refractionTexture);
  36449. }
  36450. return activeTextures;
  36451. };
  36452. PBRMaterial.prototype.hasTexture = function (texture) {
  36453. if (_super.prototype.hasTexture.call(this, texture)) {
  36454. return true;
  36455. }
  36456. if (this._albedoTexture === texture) {
  36457. return true;
  36458. }
  36459. if (this._ambientTexture === texture) {
  36460. return true;
  36461. }
  36462. if (this._opacityTexture === texture) {
  36463. return true;
  36464. }
  36465. if (this._reflectionTexture === texture) {
  36466. return true;
  36467. }
  36468. if (this._reflectivityTexture === texture) {
  36469. return true;
  36470. }
  36471. if (this._metallicTexture === texture) {
  36472. return true;
  36473. }
  36474. if (this._microSurfaceTexture === texture) {
  36475. return true;
  36476. }
  36477. if (this._bumpTexture === texture) {
  36478. return true;
  36479. }
  36480. if (this._lightmapTexture === texture) {
  36481. return true;
  36482. }
  36483. if (this._refractionTexture === texture) {
  36484. return true;
  36485. }
  36486. return false;
  36487. };
  36488. PBRMaterial.prototype.clone = function (name) {
  36489. var _this = this;
  36490. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36491. clone.id = name;
  36492. clone.name = name;
  36493. return clone;
  36494. };
  36495. PBRMaterial.prototype.serialize = function () {
  36496. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36497. serializationObject.customType = "BABYLON.PBRMaterial";
  36498. return serializationObject;
  36499. };
  36500. // Statics
  36501. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36502. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36503. };
  36504. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36505. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36506. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36507. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36508. __decorate([
  36509. BABYLON.serialize(),
  36510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36511. ], PBRMaterial.prototype, "directIntensity", void 0);
  36512. __decorate([
  36513. BABYLON.serialize(),
  36514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36515. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36516. __decorate([
  36517. BABYLON.serialize(),
  36518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36519. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36520. __decorate([
  36521. BABYLON.serialize(),
  36522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36523. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36524. __decorate([
  36525. BABYLON.serialize(),
  36526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36527. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36528. __decorate([
  36529. BABYLON.serializeAsTexture(),
  36530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36531. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36532. __decorate([
  36533. BABYLON.serializeAsTexture(),
  36534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36535. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36536. __decorate([
  36537. BABYLON.serialize(),
  36538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36539. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36540. __decorate([
  36541. BABYLON.serializeAsTexture(),
  36542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36543. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36544. __decorate([
  36545. BABYLON.serializeAsTexture(),
  36546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36547. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36548. __decorate([
  36549. BABYLON.serializeAsTexture(),
  36550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36551. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36552. __decorate([
  36553. BABYLON.serializeAsTexture(),
  36554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36555. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36556. __decorate([
  36557. BABYLON.serializeAsTexture(),
  36558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36559. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36560. __decorate([
  36561. BABYLON.serialize(),
  36562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36563. ], PBRMaterial.prototype, "metallic", void 0);
  36564. __decorate([
  36565. BABYLON.serialize(),
  36566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36567. ], PBRMaterial.prototype, "roughness", void 0);
  36568. __decorate([
  36569. BABYLON.serializeAsTexture(),
  36570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36571. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36572. __decorate([
  36573. BABYLON.serializeAsTexture(),
  36574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36575. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36576. __decorate([
  36577. BABYLON.serializeAsTexture(),
  36578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36579. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36580. __decorate([
  36581. BABYLON.serializeAsTexture(),
  36582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36583. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36584. __decorate([
  36585. BABYLON.serializeAsColor3("ambient"),
  36586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36587. ], PBRMaterial.prototype, "ambientColor", void 0);
  36588. __decorate([
  36589. BABYLON.serializeAsColor3("albedo"),
  36590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36591. ], PBRMaterial.prototype, "albedoColor", void 0);
  36592. __decorate([
  36593. BABYLON.serializeAsColor3("reflectivity"),
  36594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36595. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36596. __decorate([
  36597. BABYLON.serializeAsColor3("reflection"),
  36598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36599. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36600. __decorate([
  36601. BABYLON.serializeAsColor3("emissive"),
  36602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36603. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36604. __decorate([
  36605. BABYLON.serialize(),
  36606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36607. ], PBRMaterial.prototype, "microSurface", void 0);
  36608. __decorate([
  36609. BABYLON.serialize(),
  36610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36611. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36612. __decorate([
  36613. BABYLON.serialize(),
  36614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36615. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36616. __decorate([
  36617. BABYLON.serialize(),
  36618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36619. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36620. __decorate([
  36621. BABYLON.serialize(),
  36622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36623. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36624. __decorate([
  36625. BABYLON.serialize(),
  36626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36627. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36628. __decorate([
  36629. BABYLON.serialize(),
  36630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36631. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  36632. __decorate([
  36633. BABYLON.serialize(),
  36634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36635. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  36636. __decorate([
  36637. BABYLON.serialize(),
  36638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36639. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36640. __decorate([
  36641. BABYLON.serialize(),
  36642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36643. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36644. __decorate([
  36645. BABYLON.serialize(),
  36646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36647. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36648. __decorate([
  36649. BABYLON.serialize(),
  36650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36651. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36652. __decorate([
  36653. BABYLON.serialize(),
  36654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36655. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36656. __decorate([
  36657. BABYLON.serialize(),
  36658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36659. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36660. __decorate([
  36661. BABYLON.serialize(),
  36662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36663. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36664. __decorate([
  36665. BABYLON.serialize(),
  36666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36667. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36668. __decorate([
  36669. BABYLON.serialize(),
  36670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36671. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36672. __decorate([
  36673. BABYLON.serialize(),
  36674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36675. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36676. __decorate([
  36677. BABYLON.serialize(),
  36678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36679. ], PBRMaterial.prototype, "useParallax", void 0);
  36680. __decorate([
  36681. BABYLON.serialize(),
  36682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36683. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36684. __decorate([
  36685. BABYLON.serialize(),
  36686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36687. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36688. __decorate([
  36689. BABYLON.serialize(),
  36690. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36691. ], PBRMaterial.prototype, "disableLighting", void 0);
  36692. __decorate([
  36693. BABYLON.serialize(),
  36694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36695. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  36696. __decorate([
  36697. BABYLON.serialize(),
  36698. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36699. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36700. __decorate([
  36701. BABYLON.serialize(),
  36702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36703. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36704. __decorate([
  36705. BABYLON.serialize(),
  36706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36707. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36708. __decorate([
  36709. BABYLON.serialize(),
  36710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36711. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36712. __decorate([
  36713. BABYLON.serialize(),
  36714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36715. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36716. __decorate([
  36717. BABYLON.serializeAsTexture(),
  36718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36719. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36720. __decorate([
  36721. BABYLON.serialize(),
  36722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36723. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  36724. return PBRMaterial;
  36725. }(BABYLON.PBRBaseMaterial));
  36726. BABYLON.PBRMaterial = PBRMaterial;
  36727. })(BABYLON || (BABYLON = {}));
  36728. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36729. var BABYLON;
  36730. (function (BABYLON) {
  36731. /**
  36732. * The PBR material of BJS following the metal roughness convention.
  36733. *
  36734. * This fits to the PBR convention in the GLTF definition:
  36735. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36736. */
  36737. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  36738. __extends(PBRMetallicRoughnessMaterial, _super);
  36739. /**
  36740. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36741. *
  36742. * @param name The material name
  36743. * @param scene The scene the material will be use in.
  36744. */
  36745. function PBRMetallicRoughnessMaterial(name, scene) {
  36746. var _this = _super.call(this, name, scene) || this;
  36747. _this._useRoughnessFromMetallicTextureAlpha = false;
  36748. _this._useRoughnessFromMetallicTextureGreen = true;
  36749. _this._useMetallnessFromMetallicTextureBlue = true;
  36750. return _this;
  36751. }
  36752. /**
  36753. * Return the currrent class name of the material.
  36754. */
  36755. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36756. return "PBRMetallicRoughnessMaterial";
  36757. };
  36758. /**
  36759. * Return the active textures of the material.
  36760. */
  36761. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36762. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36763. if (this.baseTexture) {
  36764. activeTextures.push(this.baseTexture);
  36765. }
  36766. if (this.metallicRoughnessTexture) {
  36767. activeTextures.push(this.metallicRoughnessTexture);
  36768. }
  36769. return activeTextures;
  36770. };
  36771. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  36772. if (_super.prototype.hasTexture.call(this, texture)) {
  36773. return true;
  36774. }
  36775. if (this.baseTexture === texture) {
  36776. return true;
  36777. }
  36778. if (this.metallicRoughnessTexture === texture) {
  36779. return true;
  36780. }
  36781. return false;
  36782. };
  36783. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36784. var _this = this;
  36785. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36786. clone.id = name;
  36787. clone.name = name;
  36788. return clone;
  36789. };
  36790. /**
  36791. * Serialize the material to a parsable JSON object.
  36792. */
  36793. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36794. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36795. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36796. return serializationObject;
  36797. };
  36798. /**
  36799. * Parses a JSON object correponding to the serialize function.
  36800. */
  36801. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36802. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36803. };
  36804. __decorate([
  36805. BABYLON.serializeAsColor3(),
  36806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36807. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36808. __decorate([
  36809. BABYLON.serializeAsTexture(),
  36810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36811. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36812. __decorate([
  36813. BABYLON.serialize(),
  36814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36815. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36816. __decorate([
  36817. BABYLON.serialize(),
  36818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36819. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36820. __decorate([
  36821. BABYLON.serializeAsTexture(),
  36822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36823. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36824. return PBRMetallicRoughnessMaterial;
  36825. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36826. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36827. })(BABYLON || (BABYLON = {}));
  36828. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36829. var BABYLON;
  36830. (function (BABYLON) {
  36831. /**
  36832. * The PBR material of BJS following the specular glossiness convention.
  36833. *
  36834. * This fits to the PBR convention in the GLTF definition:
  36835. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36836. */
  36837. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  36838. __extends(PBRSpecularGlossinessMaterial, _super);
  36839. /**
  36840. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36841. *
  36842. * @param name The material name
  36843. * @param scene The scene the material will be use in.
  36844. */
  36845. function PBRSpecularGlossinessMaterial(name, scene) {
  36846. var _this = _super.call(this, name, scene) || this;
  36847. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36848. return _this;
  36849. }
  36850. /**
  36851. * Return the currrent class name of the material.
  36852. */
  36853. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36854. return "PBRSpecularGlossinessMaterial";
  36855. };
  36856. /**
  36857. * Return the active textures of the material.
  36858. */
  36859. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36860. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36861. if (this.diffuseTexture) {
  36862. activeTextures.push(this.diffuseTexture);
  36863. }
  36864. if (this.specularGlossinessTexture) {
  36865. activeTextures.push(this.specularGlossinessTexture);
  36866. }
  36867. return activeTextures;
  36868. };
  36869. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  36870. if (_super.prototype.hasTexture.call(this, texture)) {
  36871. return true;
  36872. }
  36873. if (this.diffuseTexture === texture) {
  36874. return true;
  36875. }
  36876. if (this.specularGlossinessTexture === texture) {
  36877. return true;
  36878. }
  36879. return false;
  36880. };
  36881. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  36882. var _this = this;
  36883. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  36884. clone.id = name;
  36885. clone.name = name;
  36886. return clone;
  36887. };
  36888. /**
  36889. * Serialize the material to a parsable JSON object.
  36890. */
  36891. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36892. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36893. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36894. return serializationObject;
  36895. };
  36896. /**
  36897. * Parses a JSON object correponding to the serialize function.
  36898. */
  36899. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36900. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36901. };
  36902. __decorate([
  36903. BABYLON.serializeAsColor3("diffuse"),
  36904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36905. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36906. __decorate([
  36907. BABYLON.serializeAsTexture(),
  36908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36909. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36910. __decorate([
  36911. BABYLON.serializeAsColor3("specular"),
  36912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36913. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36914. __decorate([
  36915. BABYLON.serialize(),
  36916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36917. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36918. __decorate([
  36919. BABYLON.serializeAsTexture(),
  36920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36921. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36922. return PBRSpecularGlossinessMaterial;
  36923. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36924. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36925. })(BABYLON || (BABYLON = {}));
  36926. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36927. var BABYLON;
  36928. (function (BABYLON) {
  36929. BABYLON.CameraInputTypes = {};
  36930. var CameraInputsManager = /** @class */ (function () {
  36931. function CameraInputsManager(camera) {
  36932. this.attached = {};
  36933. this.camera = camera;
  36934. this.checkInputs = function () { };
  36935. }
  36936. CameraInputsManager.prototype.add = function (input) {
  36937. var type = input.getSimpleName();
  36938. if (this.attached[type]) {
  36939. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  36940. return;
  36941. }
  36942. this.attached[type] = input;
  36943. input.camera = this.camera;
  36944. //for checkInputs, we are dynamically creating a function
  36945. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  36946. if (input.checkInputs) {
  36947. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36948. }
  36949. if (this.attachedElement) {
  36950. input.attachControl(this.attachedElement);
  36951. }
  36952. };
  36953. CameraInputsManager.prototype.remove = function (inputToRemove) {
  36954. for (var cam in this.attached) {
  36955. var input = this.attached[cam];
  36956. if (input === inputToRemove) {
  36957. input.detachControl(this.attachedElement);
  36958. input.camera = null;
  36959. delete this.attached[cam];
  36960. this.rebuildInputCheck();
  36961. }
  36962. }
  36963. };
  36964. CameraInputsManager.prototype.removeByType = function (inputType) {
  36965. for (var cam in this.attached) {
  36966. var input = this.attached[cam];
  36967. if (input.getClassName() === inputType) {
  36968. input.detachControl(this.attachedElement);
  36969. input.camera = null;
  36970. delete this.attached[cam];
  36971. this.rebuildInputCheck();
  36972. }
  36973. }
  36974. };
  36975. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  36976. var current = this.checkInputs;
  36977. return function () {
  36978. current();
  36979. fn();
  36980. };
  36981. };
  36982. CameraInputsManager.prototype.attachInput = function (input) {
  36983. if (this.attachedElement) {
  36984. input.attachControl(this.attachedElement, this.noPreventDefault);
  36985. }
  36986. };
  36987. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  36988. if (noPreventDefault === void 0) { noPreventDefault = false; }
  36989. if (this.attachedElement) {
  36990. return;
  36991. }
  36992. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  36993. this.attachedElement = element;
  36994. this.noPreventDefault = noPreventDefault;
  36995. for (var cam in this.attached) {
  36996. this.attached[cam].attachControl(element, noPreventDefault);
  36997. }
  36998. };
  36999. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  37000. if (disconnect === void 0) { disconnect = false; }
  37001. if (this.attachedElement !== element) {
  37002. return;
  37003. }
  37004. for (var cam in this.attached) {
  37005. this.attached[cam].detachControl(element);
  37006. if (disconnect) {
  37007. this.attached[cam].camera = null;
  37008. }
  37009. }
  37010. this.attachedElement = null;
  37011. };
  37012. CameraInputsManager.prototype.rebuildInputCheck = function () {
  37013. this.checkInputs = function () { };
  37014. for (var cam in this.attached) {
  37015. var input = this.attached[cam];
  37016. if (input.checkInputs) {
  37017. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37018. }
  37019. }
  37020. };
  37021. CameraInputsManager.prototype.clear = function () {
  37022. if (this.attachedElement) {
  37023. this.detachElement(this.attachedElement, true);
  37024. }
  37025. this.attached = {};
  37026. this.attachedElement = null;
  37027. this.checkInputs = function () { };
  37028. };
  37029. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  37030. var inputs = {};
  37031. for (var cam in this.attached) {
  37032. var input = this.attached[cam];
  37033. var res = BABYLON.SerializationHelper.Serialize(input);
  37034. inputs[input.getClassName()] = res;
  37035. }
  37036. serializedCamera.inputsmgr = inputs;
  37037. };
  37038. CameraInputsManager.prototype.parse = function (parsedCamera) {
  37039. var parsedInputs = parsedCamera.inputsmgr;
  37040. if (parsedInputs) {
  37041. this.clear();
  37042. for (var n in parsedInputs) {
  37043. var construct = BABYLON.CameraInputTypes[n];
  37044. if (construct) {
  37045. var parsedinput = parsedInputs[n];
  37046. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  37047. this.add(input);
  37048. }
  37049. }
  37050. }
  37051. else {
  37052. //2016-03-08 this part is for managing backward compatibility
  37053. for (var n in this.attached) {
  37054. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  37055. if (construct) {
  37056. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  37057. this.remove(this.attached[n]);
  37058. this.add(input);
  37059. }
  37060. }
  37061. }
  37062. };
  37063. return CameraInputsManager;
  37064. }());
  37065. BABYLON.CameraInputsManager = CameraInputsManager;
  37066. })(BABYLON || (BABYLON = {}));
  37067. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  37068. var BABYLON;
  37069. (function (BABYLON) {
  37070. var FreeCameraMouseInput = /** @class */ (function () {
  37071. function FreeCameraMouseInput(touchEnabled) {
  37072. if (touchEnabled === void 0) { touchEnabled = true; }
  37073. this.touchEnabled = touchEnabled;
  37074. this.buttons = [0, 1, 2];
  37075. this.angularSensibility = 2000.0;
  37076. this.previousPosition = null;
  37077. }
  37078. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  37079. var _this = this;
  37080. var engine = this.camera.getEngine();
  37081. if (!this._pointerInput) {
  37082. this._pointerInput = function (p, s) {
  37083. var evt = p.event;
  37084. if (engine.isInVRExclusivePointerMode) {
  37085. return;
  37086. }
  37087. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37088. return;
  37089. }
  37090. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37091. return;
  37092. }
  37093. var srcElement = (evt.srcElement || evt.target);
  37094. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37095. try {
  37096. srcElement.setPointerCapture(evt.pointerId);
  37097. }
  37098. catch (e) {
  37099. //Nothing to do with the error. Execution will continue.
  37100. }
  37101. _this.previousPosition = {
  37102. x: evt.clientX,
  37103. y: evt.clientY
  37104. };
  37105. if (!noPreventDefault) {
  37106. evt.preventDefault();
  37107. element.focus();
  37108. }
  37109. }
  37110. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37111. try {
  37112. srcElement.releasePointerCapture(evt.pointerId);
  37113. }
  37114. catch (e) {
  37115. //Nothing to do with the error.
  37116. }
  37117. _this.previousPosition = null;
  37118. if (!noPreventDefault) {
  37119. evt.preventDefault();
  37120. }
  37121. }
  37122. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37123. if (!_this.previousPosition || engine.isPointerLock) {
  37124. return;
  37125. }
  37126. var offsetX = evt.clientX - _this.previousPosition.x;
  37127. var offsetY = evt.clientY - _this.previousPosition.y;
  37128. if (_this.camera.getScene().useRightHandedSystem) {
  37129. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37130. }
  37131. else {
  37132. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37133. }
  37134. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37135. _this.previousPosition = {
  37136. x: evt.clientX,
  37137. y: evt.clientY
  37138. };
  37139. if (!noPreventDefault) {
  37140. evt.preventDefault();
  37141. }
  37142. }
  37143. };
  37144. }
  37145. this._onMouseMove = function (evt) {
  37146. if (!engine.isPointerLock) {
  37147. return;
  37148. }
  37149. if (engine.isInVRExclusivePointerMode) {
  37150. return;
  37151. }
  37152. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37153. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37154. if (_this.camera.getScene().useRightHandedSystem) {
  37155. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37156. }
  37157. else {
  37158. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37159. }
  37160. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37161. _this.previousPosition = null;
  37162. if (!noPreventDefault) {
  37163. evt.preventDefault();
  37164. }
  37165. };
  37166. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37167. element.addEventListener("mousemove", this._onMouseMove, false);
  37168. };
  37169. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37170. if (this._observer && element) {
  37171. this.camera.getScene().onPointerObservable.remove(this._observer);
  37172. if (this._onMouseMove) {
  37173. element.removeEventListener("mousemove", this._onMouseMove);
  37174. }
  37175. this._observer = null;
  37176. this._onMouseMove = null;
  37177. this.previousPosition = null;
  37178. }
  37179. };
  37180. FreeCameraMouseInput.prototype.getClassName = function () {
  37181. return "FreeCameraMouseInput";
  37182. };
  37183. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37184. return "mouse";
  37185. };
  37186. __decorate([
  37187. BABYLON.serialize()
  37188. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37189. __decorate([
  37190. BABYLON.serialize()
  37191. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37192. return FreeCameraMouseInput;
  37193. }());
  37194. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37195. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37196. })(BABYLON || (BABYLON = {}));
  37197. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37198. var BABYLON;
  37199. (function (BABYLON) {
  37200. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37201. function FreeCameraKeyboardMoveInput() {
  37202. this._keys = new Array();
  37203. this.keysUp = [38];
  37204. this.keysDown = [40];
  37205. this.keysLeft = [37];
  37206. this.keysRight = [39];
  37207. }
  37208. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37209. var _this = this;
  37210. if (this._onCanvasBlurObserver) {
  37211. return;
  37212. }
  37213. this._scene = this.camera.getScene();
  37214. this._engine = this._scene.getEngine();
  37215. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37216. _this._keys = [];
  37217. });
  37218. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37219. var evt = info.event;
  37220. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37221. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37222. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37223. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37224. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37225. var index = _this._keys.indexOf(evt.keyCode);
  37226. if (index === -1) {
  37227. _this._keys.push(evt.keyCode);
  37228. }
  37229. if (!noPreventDefault) {
  37230. evt.preventDefault();
  37231. }
  37232. }
  37233. }
  37234. else {
  37235. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37236. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37237. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37238. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37239. var index = _this._keys.indexOf(evt.keyCode);
  37240. if (index >= 0) {
  37241. _this._keys.splice(index, 1);
  37242. }
  37243. if (!noPreventDefault) {
  37244. evt.preventDefault();
  37245. }
  37246. }
  37247. }
  37248. });
  37249. };
  37250. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37251. if (this._scene) {
  37252. if (this._onKeyboardObserver) {
  37253. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37254. }
  37255. if (this._onCanvasBlurObserver) {
  37256. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37257. }
  37258. this._onKeyboardObserver = null;
  37259. this._onCanvasBlurObserver = null;
  37260. }
  37261. this._keys = [];
  37262. };
  37263. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37264. if (this._onKeyboardObserver) {
  37265. var camera = this.camera;
  37266. // Keyboard
  37267. for (var index = 0; index < this._keys.length; index++) {
  37268. var keyCode = this._keys[index];
  37269. var speed = camera._computeLocalCameraSpeed();
  37270. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37271. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37272. }
  37273. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37274. camera._localDirection.copyFromFloats(0, 0, speed);
  37275. }
  37276. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37277. camera._localDirection.copyFromFloats(speed, 0, 0);
  37278. }
  37279. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37280. camera._localDirection.copyFromFloats(0, 0, -speed);
  37281. }
  37282. if (camera.getScene().useRightHandedSystem) {
  37283. camera._localDirection.z *= -1;
  37284. }
  37285. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37286. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37287. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37288. }
  37289. }
  37290. };
  37291. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37292. return "FreeCameraKeyboardMoveInput";
  37293. };
  37294. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37295. this._keys = [];
  37296. };
  37297. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37298. return "keyboard";
  37299. };
  37300. __decorate([
  37301. BABYLON.serialize()
  37302. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37303. __decorate([
  37304. BABYLON.serialize()
  37305. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37306. __decorate([
  37307. BABYLON.serialize()
  37308. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37309. __decorate([
  37310. BABYLON.serialize()
  37311. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37312. return FreeCameraKeyboardMoveInput;
  37313. }());
  37314. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37315. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37316. })(BABYLON || (BABYLON = {}));
  37317. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  37318. var BABYLON;
  37319. (function (BABYLON) {
  37320. var FreeCameraInputsManager = /** @class */ (function (_super) {
  37321. __extends(FreeCameraInputsManager, _super);
  37322. function FreeCameraInputsManager(camera) {
  37323. return _super.call(this, camera) || this;
  37324. }
  37325. FreeCameraInputsManager.prototype.addKeyboard = function () {
  37326. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  37327. return this;
  37328. };
  37329. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  37330. if (touchEnabled === void 0) { touchEnabled = true; }
  37331. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37332. return this;
  37333. };
  37334. FreeCameraInputsManager.prototype.addGamepad = function () {
  37335. this.add(new BABYLON.FreeCameraGamepadInput());
  37336. return this;
  37337. };
  37338. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37339. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37340. return this;
  37341. };
  37342. FreeCameraInputsManager.prototype.addTouch = function () {
  37343. this.add(new BABYLON.FreeCameraTouchInput());
  37344. return this;
  37345. };
  37346. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37347. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37348. return this;
  37349. };
  37350. return FreeCameraInputsManager;
  37351. }(BABYLON.CameraInputsManager));
  37352. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37353. })(BABYLON || (BABYLON = {}));
  37354. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37355. var BABYLON;
  37356. (function (BABYLON) {
  37357. var TargetCamera = /** @class */ (function (_super) {
  37358. __extends(TargetCamera, _super);
  37359. function TargetCamera(name, position, scene) {
  37360. var _this = _super.call(this, name, position, scene) || this;
  37361. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37362. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37363. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37364. _this.speed = 2.0;
  37365. _this.noRotationConstraint = false;
  37366. _this.lockedTarget = null;
  37367. _this._currentTarget = BABYLON.Vector3.Zero();
  37368. _this._viewMatrix = BABYLON.Matrix.Zero();
  37369. _this._camMatrix = BABYLON.Matrix.Zero();
  37370. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  37371. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  37372. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  37373. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  37374. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  37375. _this._lookAtTemp = BABYLON.Matrix.Zero();
  37376. _this._tempMatrix = BABYLON.Matrix.Zero();
  37377. return _this;
  37378. }
  37379. TargetCamera.prototype.getFrontPosition = function (distance) {
  37380. var direction = this.getTarget().subtract(this.position);
  37381. direction.normalize();
  37382. direction.scaleInPlace(distance);
  37383. return this.globalPosition.add(direction);
  37384. };
  37385. TargetCamera.prototype._getLockedTargetPosition = function () {
  37386. if (!this.lockedTarget) {
  37387. return null;
  37388. }
  37389. if (this.lockedTarget.absolutePosition) {
  37390. this.lockedTarget.computeWorldMatrix();
  37391. }
  37392. return this.lockedTarget.absolutePosition || this.lockedTarget;
  37393. };
  37394. TargetCamera.prototype.storeState = function () {
  37395. this._storedPosition = this.position.clone();
  37396. this._storedRotation = this.rotation.clone();
  37397. if (this.rotationQuaternion) {
  37398. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  37399. }
  37400. return _super.prototype.storeState.call(this);
  37401. };
  37402. /**
  37403. * Restored camera state. You must call storeState() first
  37404. */
  37405. TargetCamera.prototype._restoreStateValues = function () {
  37406. if (!_super.prototype._restoreStateValues.call(this)) {
  37407. return false;
  37408. }
  37409. this.position = this._storedPosition.clone();
  37410. this.rotation = this._storedRotation.clone();
  37411. if (this.rotationQuaternion) {
  37412. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  37413. }
  37414. this.cameraDirection.copyFromFloats(0, 0, 0);
  37415. this.cameraRotation.copyFromFloats(0, 0);
  37416. return true;
  37417. };
  37418. // Cache
  37419. TargetCamera.prototype._initCache = function () {
  37420. _super.prototype._initCache.call(this);
  37421. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37422. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37423. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37424. };
  37425. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  37426. if (!ignoreParentClass) {
  37427. _super.prototype._updateCache.call(this);
  37428. }
  37429. var lockedTargetPosition = this._getLockedTargetPosition();
  37430. if (!lockedTargetPosition) {
  37431. this._cache.lockedTarget = null;
  37432. }
  37433. else {
  37434. if (!this._cache.lockedTarget) {
  37435. this._cache.lockedTarget = lockedTargetPosition.clone();
  37436. }
  37437. else {
  37438. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  37439. }
  37440. }
  37441. this._cache.rotation.copyFrom(this.rotation);
  37442. if (this.rotationQuaternion)
  37443. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37444. };
  37445. // Synchronized
  37446. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  37447. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  37448. return false;
  37449. }
  37450. var lockedTargetPosition = this._getLockedTargetPosition();
  37451. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  37452. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  37453. };
  37454. // Methods
  37455. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  37456. var engine = this.getEngine();
  37457. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  37458. };
  37459. // Target
  37460. TargetCamera.prototype.setTarget = function (target) {
  37461. this.upVector.normalize();
  37462. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  37463. this._camMatrix.invert();
  37464. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  37465. var vDir = target.subtract(this.position);
  37466. if (vDir.x >= 0.0) {
  37467. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  37468. }
  37469. else {
  37470. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  37471. }
  37472. this.rotation.z = 0;
  37473. if (isNaN(this.rotation.x)) {
  37474. this.rotation.x = 0;
  37475. }
  37476. if (isNaN(this.rotation.y)) {
  37477. this.rotation.y = 0;
  37478. }
  37479. if (isNaN(this.rotation.z)) {
  37480. this.rotation.z = 0;
  37481. }
  37482. if (this.rotationQuaternion) {
  37483. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37484. }
  37485. };
  37486. /**
  37487. * Return the current target position of the camera. This value is expressed in local space.
  37488. */
  37489. TargetCamera.prototype.getTarget = function () {
  37490. return this._currentTarget;
  37491. };
  37492. TargetCamera.prototype._decideIfNeedsToMove = function () {
  37493. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37494. };
  37495. TargetCamera.prototype._updatePosition = function () {
  37496. if (this.parent) {
  37497. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  37498. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  37499. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  37500. return;
  37501. }
  37502. this.position.addInPlace(this.cameraDirection);
  37503. };
  37504. TargetCamera.prototype._checkInputs = function () {
  37505. var needToMove = this._decideIfNeedsToMove();
  37506. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  37507. // Move
  37508. if (needToMove) {
  37509. this._updatePosition();
  37510. }
  37511. // Rotate
  37512. if (needToRotate) {
  37513. this.rotation.x += this.cameraRotation.x;
  37514. this.rotation.y += this.cameraRotation.y;
  37515. //rotate, if quaternion is set and rotation was used
  37516. if (this.rotationQuaternion) {
  37517. var len = this.rotation.lengthSquared();
  37518. if (len) {
  37519. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37520. }
  37521. }
  37522. if (!this.noRotationConstraint) {
  37523. var limit = (Math.PI / 2) * 0.95;
  37524. if (this.rotation.x > limit)
  37525. this.rotation.x = limit;
  37526. if (this.rotation.x < -limit)
  37527. this.rotation.x = -limit;
  37528. }
  37529. }
  37530. // Inertia
  37531. if (needToMove) {
  37532. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  37533. this.cameraDirection.x = 0;
  37534. }
  37535. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  37536. this.cameraDirection.y = 0;
  37537. }
  37538. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  37539. this.cameraDirection.z = 0;
  37540. }
  37541. this.cameraDirection.scaleInPlace(this.inertia);
  37542. }
  37543. if (needToRotate) {
  37544. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  37545. this.cameraRotation.x = 0;
  37546. }
  37547. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  37548. this.cameraRotation.y = 0;
  37549. }
  37550. this.cameraRotation.scaleInPlace(this.inertia);
  37551. }
  37552. _super.prototype._checkInputs.call(this);
  37553. };
  37554. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  37555. if (this.rotationQuaternion) {
  37556. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  37557. }
  37558. else {
  37559. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  37560. }
  37561. //update the up vector!
  37562. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  37563. };
  37564. TargetCamera.prototype._getViewMatrix = function () {
  37565. if (!this.lockedTarget) {
  37566. // Compute
  37567. this._updateCameraRotationMatrix();
  37568. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  37569. // Computing target and final matrix
  37570. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  37571. }
  37572. else {
  37573. var targetPosition = this._getLockedTargetPosition();
  37574. if (targetPosition) {
  37575. this._currentTarget.copyFrom(targetPosition);
  37576. }
  37577. }
  37578. if (this.getScene().useRightHandedSystem) {
  37579. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37580. }
  37581. else {
  37582. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37583. }
  37584. return this._viewMatrix;
  37585. };
  37586. /**
  37587. * @override
  37588. * Override Camera.createRigCamera
  37589. */
  37590. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37591. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  37592. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  37593. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  37594. if (!this.rotationQuaternion) {
  37595. this.rotationQuaternion = new BABYLON.Quaternion();
  37596. }
  37597. rigCamera._cameraRigParams = {};
  37598. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  37599. }
  37600. return rigCamera;
  37601. }
  37602. return null;
  37603. };
  37604. /**
  37605. * @override
  37606. * Override Camera._updateRigCameras
  37607. */
  37608. TargetCamera.prototype._updateRigCameras = function () {
  37609. var camLeft = this._rigCameras[0];
  37610. var camRight = this._rigCameras[1];
  37611. switch (this.cameraRigMode) {
  37612. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37613. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37614. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37615. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37616. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  37617. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  37618. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  37619. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  37620. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  37621. camLeft.setTarget(this.getTarget());
  37622. camRight.setTarget(this.getTarget());
  37623. break;
  37624. case BABYLON.Camera.RIG_MODE_VR:
  37625. if (camLeft.rotationQuaternion) {
  37626. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37627. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37628. }
  37629. else {
  37630. camLeft.rotation.copyFrom(this.rotation);
  37631. camRight.rotation.copyFrom(this.rotation);
  37632. }
  37633. camLeft.position.copyFrom(this.position);
  37634. camRight.position.copyFrom(this.position);
  37635. break;
  37636. }
  37637. _super.prototype._updateRigCameras.call(this);
  37638. };
  37639. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  37640. if (!this._rigCamTransformMatrix) {
  37641. this._rigCamTransformMatrix = new BABYLON.Matrix();
  37642. }
  37643. var target = this.getTarget();
  37644. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  37645. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  37646. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  37647. };
  37648. TargetCamera.prototype.getClassName = function () {
  37649. return "TargetCamera";
  37650. };
  37651. __decorate([
  37652. BABYLON.serializeAsVector3()
  37653. ], TargetCamera.prototype, "rotation", void 0);
  37654. __decorate([
  37655. BABYLON.serialize()
  37656. ], TargetCamera.prototype, "speed", void 0);
  37657. __decorate([
  37658. BABYLON.serializeAsMeshReference("lockedTargetId")
  37659. ], TargetCamera.prototype, "lockedTarget", void 0);
  37660. return TargetCamera;
  37661. }(BABYLON.Camera));
  37662. BABYLON.TargetCamera = TargetCamera;
  37663. })(BABYLON || (BABYLON = {}));
  37664. //# sourceMappingURL=babylon.targetCamera.js.map
  37665. var BABYLON;
  37666. (function (BABYLON) {
  37667. var FreeCamera = /** @class */ (function (_super) {
  37668. __extends(FreeCamera, _super);
  37669. function FreeCamera(name, position, scene) {
  37670. var _this = _super.call(this, name, position, scene) || this;
  37671. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  37672. _this.checkCollisions = false;
  37673. _this.applyGravity = false;
  37674. _this._needMoveForGravity = false;
  37675. _this._oldPosition = BABYLON.Vector3.Zero();
  37676. _this._diffPosition = BABYLON.Vector3.Zero();
  37677. _this._newPosition = BABYLON.Vector3.Zero();
  37678. // Collisions
  37679. _this._collisionMask = -1;
  37680. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37681. if (collidedMesh === void 0) { collidedMesh = null; }
  37682. //TODO move this to the collision coordinator!
  37683. if (_this.getScene().workerCollisions)
  37684. newPosition.multiplyInPlace(_this._collider.radius);
  37685. var updatePosition = function (newPos) {
  37686. _this._newPosition.copyFrom(newPos);
  37687. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  37688. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  37689. _this.position.addInPlace(_this._diffPosition);
  37690. if (_this.onCollide && collidedMesh) {
  37691. _this.onCollide(collidedMesh);
  37692. }
  37693. }
  37694. };
  37695. updatePosition(newPosition);
  37696. };
  37697. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  37698. _this.inputs.addKeyboard().addMouse();
  37699. return _this;
  37700. }
  37701. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  37702. //-- begin properties for backward compatibility for inputs
  37703. get: function () {
  37704. var mouse = this.inputs.attached["mouse"];
  37705. if (mouse)
  37706. return mouse.angularSensibility;
  37707. return 0;
  37708. },
  37709. set: function (value) {
  37710. var mouse = this.inputs.attached["mouse"];
  37711. if (mouse)
  37712. mouse.angularSensibility = value;
  37713. },
  37714. enumerable: true,
  37715. configurable: true
  37716. });
  37717. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  37718. get: function () {
  37719. var keyboard = this.inputs.attached["keyboard"];
  37720. if (keyboard)
  37721. return keyboard.keysUp;
  37722. return [];
  37723. },
  37724. set: function (value) {
  37725. var keyboard = this.inputs.attached["keyboard"];
  37726. if (keyboard)
  37727. keyboard.keysUp = value;
  37728. },
  37729. enumerable: true,
  37730. configurable: true
  37731. });
  37732. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  37733. get: function () {
  37734. var keyboard = this.inputs.attached["keyboard"];
  37735. if (keyboard)
  37736. return keyboard.keysDown;
  37737. return [];
  37738. },
  37739. set: function (value) {
  37740. var keyboard = this.inputs.attached["keyboard"];
  37741. if (keyboard)
  37742. keyboard.keysDown = value;
  37743. },
  37744. enumerable: true,
  37745. configurable: true
  37746. });
  37747. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  37748. get: function () {
  37749. var keyboard = this.inputs.attached["keyboard"];
  37750. if (keyboard)
  37751. return keyboard.keysLeft;
  37752. return [];
  37753. },
  37754. set: function (value) {
  37755. var keyboard = this.inputs.attached["keyboard"];
  37756. if (keyboard)
  37757. keyboard.keysLeft = value;
  37758. },
  37759. enumerable: true,
  37760. configurable: true
  37761. });
  37762. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  37763. get: function () {
  37764. var keyboard = this.inputs.attached["keyboard"];
  37765. if (keyboard)
  37766. return keyboard.keysRight;
  37767. return [];
  37768. },
  37769. set: function (value) {
  37770. var keyboard = this.inputs.attached["keyboard"];
  37771. if (keyboard)
  37772. keyboard.keysRight = value;
  37773. },
  37774. enumerable: true,
  37775. configurable: true
  37776. });
  37777. // Controls
  37778. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37779. this.inputs.attachElement(element, noPreventDefault);
  37780. };
  37781. FreeCamera.prototype.detachControl = function (element) {
  37782. this.inputs.detachElement(element);
  37783. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37784. this.cameraRotation = new BABYLON.Vector2(0, 0);
  37785. };
  37786. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  37787. get: function () {
  37788. return this._collisionMask;
  37789. },
  37790. set: function (mask) {
  37791. this._collisionMask = !isNaN(mask) ? mask : -1;
  37792. },
  37793. enumerable: true,
  37794. configurable: true
  37795. });
  37796. FreeCamera.prototype._collideWithWorld = function (displacement) {
  37797. var globalPosition;
  37798. if (this.parent) {
  37799. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  37800. }
  37801. else {
  37802. globalPosition = this.position;
  37803. }
  37804. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  37805. if (!this._collider) {
  37806. this._collider = new BABYLON.Collider();
  37807. }
  37808. this._collider.radius = this.ellipsoid;
  37809. this._collider.collisionMask = this._collisionMask;
  37810. //no need for clone, as long as gravity is not on.
  37811. var actualDisplacement = displacement;
  37812. //add gravity to the direction to prevent the dual-collision checking
  37813. if (this.applyGravity) {
  37814. //this prevents mending with cameraDirection, a global variable of the free camera class.
  37815. actualDisplacement = displacement.add(this.getScene().gravity);
  37816. }
  37817. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37818. };
  37819. FreeCamera.prototype._checkInputs = function () {
  37820. if (!this._localDirection) {
  37821. this._localDirection = BABYLON.Vector3.Zero();
  37822. this._transformedDirection = BABYLON.Vector3.Zero();
  37823. }
  37824. this.inputs.checkInputs();
  37825. _super.prototype._checkInputs.call(this);
  37826. };
  37827. FreeCamera.prototype._decideIfNeedsToMove = function () {
  37828. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37829. };
  37830. FreeCamera.prototype._updatePosition = function () {
  37831. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  37832. this._collideWithWorld(this.cameraDirection);
  37833. }
  37834. else {
  37835. _super.prototype._updatePosition.call(this);
  37836. }
  37837. };
  37838. FreeCamera.prototype.dispose = function () {
  37839. this.inputs.clear();
  37840. _super.prototype.dispose.call(this);
  37841. };
  37842. FreeCamera.prototype.getClassName = function () {
  37843. return "FreeCamera";
  37844. };
  37845. __decorate([
  37846. BABYLON.serializeAsVector3()
  37847. ], FreeCamera.prototype, "ellipsoid", void 0);
  37848. __decorate([
  37849. BABYLON.serialize()
  37850. ], FreeCamera.prototype, "checkCollisions", void 0);
  37851. __decorate([
  37852. BABYLON.serialize()
  37853. ], FreeCamera.prototype, "applyGravity", void 0);
  37854. return FreeCamera;
  37855. }(BABYLON.TargetCamera));
  37856. BABYLON.FreeCamera = FreeCamera;
  37857. })(BABYLON || (BABYLON = {}));
  37858. //# sourceMappingURL=babylon.freeCamera.js.map
  37859. var BABYLON;
  37860. (function (BABYLON) {
  37861. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  37862. function ArcRotateCameraKeyboardMoveInput() {
  37863. this._keys = new Array();
  37864. this.keysUp = [38];
  37865. this.keysDown = [40];
  37866. this.keysLeft = [37];
  37867. this.keysRight = [39];
  37868. this.keysReset = [220];
  37869. this.panningSensibility = 50.0;
  37870. this.zoomingSensibility = 25.0;
  37871. this.useAltToZoom = true;
  37872. }
  37873. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37874. var _this = this;
  37875. if (this._onCanvasBlurObserver) {
  37876. return;
  37877. }
  37878. this._scene = this.camera.getScene();
  37879. this._engine = this._scene.getEngine();
  37880. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37881. _this._keys = [];
  37882. });
  37883. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37884. var evt = info.event;
  37885. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37886. _this._ctrlPressed = evt.ctrlKey;
  37887. _this._altPressed = evt.altKey;
  37888. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37889. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37890. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37891. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37892. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37893. var index = _this._keys.indexOf(evt.keyCode);
  37894. if (index === -1) {
  37895. _this._keys.push(evt.keyCode);
  37896. }
  37897. if (evt.preventDefault) {
  37898. if (!noPreventDefault) {
  37899. evt.preventDefault();
  37900. }
  37901. }
  37902. }
  37903. }
  37904. else {
  37905. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37906. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37907. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37908. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37909. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37910. var index = _this._keys.indexOf(evt.keyCode);
  37911. if (index >= 0) {
  37912. _this._keys.splice(index, 1);
  37913. }
  37914. if (evt.preventDefault) {
  37915. if (!noPreventDefault) {
  37916. evt.preventDefault();
  37917. }
  37918. }
  37919. }
  37920. }
  37921. });
  37922. };
  37923. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37924. if (this._scene) {
  37925. if (this._onKeyboardObserver) {
  37926. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37927. }
  37928. if (this._onCanvasBlurObserver) {
  37929. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37930. }
  37931. this._onKeyboardObserver = null;
  37932. this._onCanvasBlurObserver = null;
  37933. }
  37934. this._keys = [];
  37935. };
  37936. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37937. if (this._onKeyboardObserver) {
  37938. var camera = this.camera;
  37939. for (var index = 0; index < this._keys.length; index++) {
  37940. var keyCode = this._keys[index];
  37941. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37942. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37943. camera.inertialPanningX -= 1 / this.panningSensibility;
  37944. }
  37945. else {
  37946. camera.inertialAlphaOffset -= 0.01;
  37947. }
  37948. }
  37949. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37950. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37951. camera.inertialPanningY += 1 / this.panningSensibility;
  37952. }
  37953. else if (this._altPressed && this.useAltToZoom) {
  37954. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  37955. }
  37956. else {
  37957. camera.inertialBetaOffset -= 0.01;
  37958. }
  37959. }
  37960. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37961. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37962. camera.inertialPanningX += 1 / this.panningSensibility;
  37963. }
  37964. else {
  37965. camera.inertialAlphaOffset += 0.01;
  37966. }
  37967. }
  37968. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37969. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37970. camera.inertialPanningY -= 1 / this.panningSensibility;
  37971. }
  37972. else if (this._altPressed && this.useAltToZoom) {
  37973. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  37974. }
  37975. else {
  37976. camera.inertialBetaOffset += 0.01;
  37977. }
  37978. }
  37979. else if (this.keysReset.indexOf(keyCode) !== -1) {
  37980. camera.restoreState();
  37981. }
  37982. }
  37983. }
  37984. };
  37985. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  37986. return "ArcRotateCameraKeyboardMoveInput";
  37987. };
  37988. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37989. return "keyboard";
  37990. };
  37991. __decorate([
  37992. BABYLON.serialize()
  37993. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37994. __decorate([
  37995. BABYLON.serialize()
  37996. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37997. __decorate([
  37998. BABYLON.serialize()
  37999. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38000. __decorate([
  38001. BABYLON.serialize()
  38002. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38003. __decorate([
  38004. BABYLON.serialize()
  38005. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  38006. __decorate([
  38007. BABYLON.serialize()
  38008. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  38009. __decorate([
  38010. BABYLON.serialize()
  38011. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  38012. __decorate([
  38013. BABYLON.serialize()
  38014. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  38015. return ArcRotateCameraKeyboardMoveInput;
  38016. }());
  38017. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  38018. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  38019. })(BABYLON || (BABYLON = {}));
  38020. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  38021. var BABYLON;
  38022. (function (BABYLON) {
  38023. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  38024. function ArcRotateCameraMouseWheelInput() {
  38025. this.wheelPrecision = 3.0;
  38026. /**
  38027. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  38028. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  38029. */
  38030. this.wheelDeltaPercentage = 0;
  38031. }
  38032. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  38033. var _this = this;
  38034. this._wheel = function (p, s) {
  38035. //sanity check - this should be a PointerWheel event.
  38036. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  38037. return;
  38038. var event = p.event;
  38039. var delta = 0;
  38040. if (event.wheelDelta) {
  38041. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  38042. }
  38043. else if (event.detail) {
  38044. delta = -event.detail / _this.wheelPrecision;
  38045. }
  38046. if (delta)
  38047. _this.camera.inertialRadiusOffset += delta;
  38048. if (event.preventDefault) {
  38049. if (!noPreventDefault) {
  38050. event.preventDefault();
  38051. }
  38052. }
  38053. };
  38054. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  38055. };
  38056. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  38057. if (this._observer && element) {
  38058. this.camera.getScene().onPointerObservable.remove(this._observer);
  38059. this._observer = null;
  38060. this._wheel = null;
  38061. }
  38062. };
  38063. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  38064. return "ArcRotateCameraMouseWheelInput";
  38065. };
  38066. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  38067. return "mousewheel";
  38068. };
  38069. __decorate([
  38070. BABYLON.serialize()
  38071. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  38072. __decorate([
  38073. BABYLON.serialize()
  38074. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  38075. return ArcRotateCameraMouseWheelInput;
  38076. }());
  38077. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  38078. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  38079. })(BABYLON || (BABYLON = {}));
  38080. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  38081. var BABYLON;
  38082. (function (BABYLON) {
  38083. var ArcRotateCameraPointersInput = /** @class */ (function () {
  38084. function ArcRotateCameraPointersInput() {
  38085. this.buttons = [0, 1, 2];
  38086. this.angularSensibilityX = 1000.0;
  38087. this.angularSensibilityY = 1000.0;
  38088. this.pinchPrecision = 12.0;
  38089. /**
  38090. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38091. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38092. */
  38093. this.pinchDeltaPercentage = 0;
  38094. this.panningSensibility = 1000.0;
  38095. this.multiTouchPanning = true;
  38096. this.multiTouchPanAndZoom = true;
  38097. this._isPanClick = false;
  38098. this.pinchInwards = true;
  38099. }
  38100. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38101. var _this = this;
  38102. var engine = this.camera.getEngine();
  38103. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38104. var pointA = null;
  38105. var pointB = null;
  38106. var previousPinchSquaredDistance = 0;
  38107. var initialDistance = 0;
  38108. var twoFingerActivityCount = 0;
  38109. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38110. this._pointerInput = function (p, s) {
  38111. var evt = p.event;
  38112. var isTouch = p.event.pointerType === "touch";
  38113. if (engine.isInVRExclusivePointerMode) {
  38114. return;
  38115. }
  38116. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38117. return;
  38118. }
  38119. var srcElement = (evt.srcElement || evt.target);
  38120. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38121. try {
  38122. srcElement.setPointerCapture(evt.pointerId);
  38123. }
  38124. catch (e) {
  38125. //Nothing to do with the error. Execution will continue.
  38126. }
  38127. // Manage panning with pan button click
  38128. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38129. // manage pointers
  38130. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38131. if (pointA === null) {
  38132. pointA = cacheSoloPointer;
  38133. }
  38134. else if (pointB === null) {
  38135. pointB = cacheSoloPointer;
  38136. }
  38137. if (!noPreventDefault) {
  38138. evt.preventDefault();
  38139. element.focus();
  38140. }
  38141. }
  38142. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38143. _this.camera.restoreState();
  38144. }
  38145. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38146. try {
  38147. srcElement.releasePointerCapture(evt.pointerId);
  38148. }
  38149. catch (e) {
  38150. //Nothing to do with the error.
  38151. }
  38152. cacheSoloPointer = null;
  38153. previousPinchSquaredDistance = 0;
  38154. previousMultiTouchPanPosition.isPaning = false;
  38155. previousMultiTouchPanPosition.isPinching = false;
  38156. twoFingerActivityCount = 0;
  38157. initialDistance = 0;
  38158. if (!isTouch) {
  38159. pointB = null; // Mouse and pen are mono pointer
  38160. }
  38161. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38162. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38163. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38164. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38165. if (engine.badOS) {
  38166. pointA = pointB = null;
  38167. }
  38168. else {
  38169. //only remove the impacted pointer in case of multitouch allowing on most
  38170. //platforms switching from rotate to zoom and pan seamlessly.
  38171. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38172. pointA = pointB;
  38173. pointB = null;
  38174. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38175. }
  38176. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38177. pointB = null;
  38178. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38179. }
  38180. else {
  38181. pointA = pointB = null;
  38182. }
  38183. }
  38184. if (!noPreventDefault) {
  38185. evt.preventDefault();
  38186. }
  38187. }
  38188. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38189. if (!noPreventDefault) {
  38190. evt.preventDefault();
  38191. }
  38192. // One button down
  38193. if (pointA && pointB === null && cacheSoloPointer) {
  38194. if (_this.panningSensibility !== 0 &&
  38195. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38196. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38197. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38198. }
  38199. else {
  38200. var offsetX = evt.clientX - cacheSoloPointer.x;
  38201. var offsetY = evt.clientY - cacheSoloPointer.y;
  38202. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38203. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38204. }
  38205. cacheSoloPointer.x = evt.clientX;
  38206. cacheSoloPointer.y = evt.clientY;
  38207. }
  38208. else if (pointA && pointB) {
  38209. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38210. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38211. ed.x = evt.clientX;
  38212. ed.y = evt.clientY;
  38213. var direction = _this.pinchInwards ? 1 : -1;
  38214. var distX = pointA.x - pointB.x;
  38215. var distY = pointA.y - pointB.y;
  38216. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38217. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38218. if (previousPinchSquaredDistance === 0) {
  38219. initialDistance = pinchDistance;
  38220. previousPinchSquaredDistance = pinchSquaredDistance;
  38221. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38222. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38223. return;
  38224. }
  38225. if (_this.multiTouchPanAndZoom) {
  38226. if (_this.pinchDeltaPercentage) {
  38227. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38228. }
  38229. else {
  38230. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38231. (_this.pinchPrecision *
  38232. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38233. direction);
  38234. }
  38235. if (_this.panningSensibility !== 0) {
  38236. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38237. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38238. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38239. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38240. previousMultiTouchPanPosition.x = pointersCenterX;
  38241. previousMultiTouchPanPosition.y = pointersCenterY;
  38242. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38243. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38244. }
  38245. }
  38246. else {
  38247. twoFingerActivityCount++;
  38248. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38249. if (_this.pinchDeltaPercentage) {
  38250. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38251. }
  38252. else {
  38253. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38254. (_this.pinchPrecision *
  38255. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38256. direction);
  38257. }
  38258. previousMultiTouchPanPosition.isPaning = false;
  38259. previousMultiTouchPanPosition.isPinching = true;
  38260. }
  38261. else {
  38262. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38263. if (!previousMultiTouchPanPosition.isPaning) {
  38264. previousMultiTouchPanPosition.isPaning = true;
  38265. previousMultiTouchPanPosition.isPinching = false;
  38266. previousMultiTouchPanPosition.x = ed.x;
  38267. previousMultiTouchPanPosition.y = ed.y;
  38268. return;
  38269. }
  38270. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38271. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38272. }
  38273. }
  38274. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38275. previousMultiTouchPanPosition.x = ed.x;
  38276. previousMultiTouchPanPosition.y = ed.y;
  38277. }
  38278. }
  38279. previousPinchSquaredDistance = pinchSquaredDistance;
  38280. }
  38281. }
  38282. };
  38283. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38284. this._onContextMenu = function (evt) {
  38285. evt.preventDefault();
  38286. };
  38287. if (!this.camera._useCtrlForPanning) {
  38288. element.addEventListener("contextmenu", this._onContextMenu, false);
  38289. }
  38290. this._onLostFocus = function () {
  38291. //this._keys = [];
  38292. pointA = pointB = null;
  38293. previousPinchSquaredDistance = 0;
  38294. previousMultiTouchPanPosition.isPaning = false;
  38295. previousMultiTouchPanPosition.isPinching = false;
  38296. twoFingerActivityCount = 0;
  38297. cacheSoloPointer = null;
  38298. initialDistance = 0;
  38299. };
  38300. this._onMouseMove = function (evt) {
  38301. if (!engine.isPointerLock) {
  38302. return;
  38303. }
  38304. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38305. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38306. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38307. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38308. if (!noPreventDefault) {
  38309. evt.preventDefault();
  38310. }
  38311. };
  38312. this._onGestureStart = function (e) {
  38313. if (window.MSGesture === undefined) {
  38314. return;
  38315. }
  38316. if (!_this._MSGestureHandler) {
  38317. _this._MSGestureHandler = new MSGesture();
  38318. _this._MSGestureHandler.target = element;
  38319. }
  38320. _this._MSGestureHandler.addPointer(e.pointerId);
  38321. };
  38322. this._onGesture = function (e) {
  38323. _this.camera.radius *= e.scale;
  38324. if (e.preventDefault) {
  38325. if (!noPreventDefault) {
  38326. e.stopPropagation();
  38327. e.preventDefault();
  38328. }
  38329. }
  38330. };
  38331. element.addEventListener("mousemove", this._onMouseMove, false);
  38332. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38333. element.addEventListener("MSGestureChange", this._onGesture, false);
  38334. BABYLON.Tools.RegisterTopRootEvents([
  38335. { name: "blur", handler: this._onLostFocus }
  38336. ]);
  38337. };
  38338. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38339. if (this._onLostFocus) {
  38340. BABYLON.Tools.UnregisterTopRootEvents([
  38341. { name: "blur", handler: this._onLostFocus }
  38342. ]);
  38343. }
  38344. if (element && this._observer) {
  38345. this.camera.getScene().onPointerObservable.remove(this._observer);
  38346. this._observer = null;
  38347. if (this._onContextMenu) {
  38348. element.removeEventListener("contextmenu", this._onContextMenu);
  38349. }
  38350. if (this._onMouseMove) {
  38351. element.removeEventListener("mousemove", this._onMouseMove);
  38352. }
  38353. if (this._onGestureStart) {
  38354. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38355. }
  38356. if (this._onGesture) {
  38357. element.removeEventListener("MSGestureChange", this._onGesture);
  38358. }
  38359. this._isPanClick = false;
  38360. this.pinchInwards = true;
  38361. this._onMouseMove = null;
  38362. this._onGestureStart = null;
  38363. this._onGesture = null;
  38364. this._MSGestureHandler = null;
  38365. this._onLostFocus = null;
  38366. this._onContextMenu = null;
  38367. }
  38368. };
  38369. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38370. return "ArcRotateCameraPointersInput";
  38371. };
  38372. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  38373. return "pointers";
  38374. };
  38375. __decorate([
  38376. BABYLON.serialize()
  38377. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  38378. __decorate([
  38379. BABYLON.serialize()
  38380. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  38381. __decorate([
  38382. BABYLON.serialize()
  38383. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  38384. __decorate([
  38385. BABYLON.serialize()
  38386. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  38387. __decorate([
  38388. BABYLON.serialize()
  38389. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  38390. __decorate([
  38391. BABYLON.serialize()
  38392. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  38393. __decorate([
  38394. BABYLON.serialize()
  38395. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  38396. __decorate([
  38397. BABYLON.serialize()
  38398. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  38399. return ArcRotateCameraPointersInput;
  38400. }());
  38401. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  38402. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  38403. })(BABYLON || (BABYLON = {}));
  38404. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  38405. var BABYLON;
  38406. (function (BABYLON) {
  38407. var ArcRotateCamera = /** @class */ (function (_super) {
  38408. __extends(ArcRotateCamera, _super);
  38409. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  38410. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  38411. _this.inertialAlphaOffset = 0;
  38412. _this.inertialBetaOffset = 0;
  38413. _this.inertialRadiusOffset = 0;
  38414. _this.lowerAlphaLimit = null;
  38415. _this.upperAlphaLimit = null;
  38416. _this.lowerBetaLimit = 0.01;
  38417. _this.upperBetaLimit = Math.PI;
  38418. _this.lowerRadiusLimit = null;
  38419. _this.upperRadiusLimit = null;
  38420. _this.inertialPanningX = 0;
  38421. _this.inertialPanningY = 0;
  38422. _this.pinchToPanMaxDistance = 20;
  38423. _this.panningDistanceLimit = null;
  38424. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  38425. _this.panningInertia = 0.9;
  38426. //-- end properties for backward compatibility for inputs
  38427. _this.zoomOnFactor = 1;
  38428. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  38429. _this.allowUpsideDown = true;
  38430. _this._viewMatrix = new BABYLON.Matrix();
  38431. // Panning
  38432. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  38433. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  38434. _this.checkCollisions = false;
  38435. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38436. _this._previousPosition = BABYLON.Vector3.Zero();
  38437. _this._collisionVelocity = BABYLON.Vector3.Zero();
  38438. _this._newPosition = BABYLON.Vector3.Zero();
  38439. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38440. if (collidedMesh === void 0) { collidedMesh = null; }
  38441. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  38442. newPosition.multiplyInPlace(_this._collider.radius);
  38443. }
  38444. if (!collidedMesh) {
  38445. _this._previousPosition.copyFrom(_this.position);
  38446. }
  38447. else {
  38448. _this.setPosition(newPosition);
  38449. if (_this.onCollide) {
  38450. _this.onCollide(collidedMesh);
  38451. }
  38452. }
  38453. // Recompute because of constraints
  38454. var cosa = Math.cos(_this.alpha);
  38455. var sina = Math.sin(_this.alpha);
  38456. var cosb = Math.cos(_this.beta);
  38457. var sinb = Math.sin(_this.beta);
  38458. if (sinb === 0) {
  38459. sinb = 0.0001;
  38460. }
  38461. var target = _this._getTargetPosition();
  38462. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  38463. _this.position.copyFrom(_this._newPosition);
  38464. var up = _this.upVector;
  38465. if (_this.allowUpsideDown && _this.beta < 0) {
  38466. up = up.clone();
  38467. up = up.negate();
  38468. }
  38469. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  38470. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  38471. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  38472. _this._collisionTriggered = false;
  38473. };
  38474. _this._target = BABYLON.Vector3.Zero();
  38475. if (target) {
  38476. _this.setTarget(target);
  38477. }
  38478. _this.alpha = alpha;
  38479. _this.beta = beta;
  38480. _this.radius = radius;
  38481. _this.getViewMatrix();
  38482. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  38483. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  38484. return _this;
  38485. }
  38486. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  38487. get: function () {
  38488. return this._target;
  38489. },
  38490. set: function (value) {
  38491. this.setTarget(value);
  38492. },
  38493. enumerable: true,
  38494. configurable: true
  38495. });
  38496. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  38497. //-- begin properties for backward compatibility for inputs
  38498. get: function () {
  38499. var pointers = this.inputs.attached["pointers"];
  38500. if (pointers)
  38501. return pointers.angularSensibilityX;
  38502. return 0;
  38503. },
  38504. set: function (value) {
  38505. var pointers = this.inputs.attached["pointers"];
  38506. if (pointers) {
  38507. pointers.angularSensibilityX = value;
  38508. }
  38509. },
  38510. enumerable: true,
  38511. configurable: true
  38512. });
  38513. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  38514. get: function () {
  38515. var pointers = this.inputs.attached["pointers"];
  38516. if (pointers)
  38517. return pointers.angularSensibilityY;
  38518. return 0;
  38519. },
  38520. set: function (value) {
  38521. var pointers = this.inputs.attached["pointers"];
  38522. if (pointers) {
  38523. pointers.angularSensibilityY = value;
  38524. }
  38525. },
  38526. enumerable: true,
  38527. configurable: true
  38528. });
  38529. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  38530. get: function () {
  38531. var pointers = this.inputs.attached["pointers"];
  38532. if (pointers)
  38533. return pointers.pinchPrecision;
  38534. return 0;
  38535. },
  38536. set: function (value) {
  38537. var pointers = this.inputs.attached["pointers"];
  38538. if (pointers) {
  38539. pointers.pinchPrecision = value;
  38540. }
  38541. },
  38542. enumerable: true,
  38543. configurable: true
  38544. });
  38545. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  38546. get: function () {
  38547. var pointers = this.inputs.attached["pointers"];
  38548. if (pointers)
  38549. return pointers.pinchDeltaPercentage;
  38550. return 0;
  38551. },
  38552. set: function (value) {
  38553. var pointers = this.inputs.attached["pointers"];
  38554. if (pointers) {
  38555. pointers.pinchDeltaPercentage = value;
  38556. }
  38557. },
  38558. enumerable: true,
  38559. configurable: true
  38560. });
  38561. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  38562. get: function () {
  38563. var pointers = this.inputs.attached["pointers"];
  38564. if (pointers)
  38565. return pointers.panningSensibility;
  38566. return 0;
  38567. },
  38568. set: function (value) {
  38569. var pointers = this.inputs.attached["pointers"];
  38570. if (pointers) {
  38571. pointers.panningSensibility = value;
  38572. }
  38573. },
  38574. enumerable: true,
  38575. configurable: true
  38576. });
  38577. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  38578. get: function () {
  38579. var keyboard = this.inputs.attached["keyboard"];
  38580. if (keyboard)
  38581. return keyboard.keysUp;
  38582. return [];
  38583. },
  38584. set: function (value) {
  38585. var keyboard = this.inputs.attached["keyboard"];
  38586. if (keyboard)
  38587. keyboard.keysUp = value;
  38588. },
  38589. enumerable: true,
  38590. configurable: true
  38591. });
  38592. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  38593. get: function () {
  38594. var keyboard = this.inputs.attached["keyboard"];
  38595. if (keyboard)
  38596. return keyboard.keysDown;
  38597. return [];
  38598. },
  38599. set: function (value) {
  38600. var keyboard = this.inputs.attached["keyboard"];
  38601. if (keyboard)
  38602. keyboard.keysDown = value;
  38603. },
  38604. enumerable: true,
  38605. configurable: true
  38606. });
  38607. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  38608. get: function () {
  38609. var keyboard = this.inputs.attached["keyboard"];
  38610. if (keyboard)
  38611. return keyboard.keysLeft;
  38612. return [];
  38613. },
  38614. set: function (value) {
  38615. var keyboard = this.inputs.attached["keyboard"];
  38616. if (keyboard)
  38617. keyboard.keysLeft = value;
  38618. },
  38619. enumerable: true,
  38620. configurable: true
  38621. });
  38622. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  38623. get: function () {
  38624. var keyboard = this.inputs.attached["keyboard"];
  38625. if (keyboard)
  38626. return keyboard.keysRight;
  38627. return [];
  38628. },
  38629. set: function (value) {
  38630. var keyboard = this.inputs.attached["keyboard"];
  38631. if (keyboard)
  38632. keyboard.keysRight = value;
  38633. },
  38634. enumerable: true,
  38635. configurable: true
  38636. });
  38637. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  38638. get: function () {
  38639. var mousewheel = this.inputs.attached["mousewheel"];
  38640. if (mousewheel)
  38641. return mousewheel.wheelPrecision;
  38642. return 0;
  38643. },
  38644. set: function (value) {
  38645. var mousewheel = this.inputs.attached["mousewheel"];
  38646. if (mousewheel)
  38647. mousewheel.wheelPrecision = value;
  38648. },
  38649. enumerable: true,
  38650. configurable: true
  38651. });
  38652. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  38653. get: function () {
  38654. var mousewheel = this.inputs.attached["mousewheel"];
  38655. if (mousewheel)
  38656. return mousewheel.wheelDeltaPercentage;
  38657. return 0;
  38658. },
  38659. set: function (value) {
  38660. var mousewheel = this.inputs.attached["mousewheel"];
  38661. if (mousewheel)
  38662. mousewheel.wheelDeltaPercentage = value;
  38663. },
  38664. enumerable: true,
  38665. configurable: true
  38666. });
  38667. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  38668. get: function () {
  38669. return this._bouncingBehavior;
  38670. },
  38671. enumerable: true,
  38672. configurable: true
  38673. });
  38674. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  38675. get: function () {
  38676. return this._bouncingBehavior != null;
  38677. },
  38678. set: function (value) {
  38679. if (value === this.useBouncingBehavior) {
  38680. return;
  38681. }
  38682. if (value) {
  38683. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  38684. this.addBehavior(this._bouncingBehavior);
  38685. }
  38686. else if (this._bouncingBehavior) {
  38687. this.removeBehavior(this._bouncingBehavior);
  38688. this._bouncingBehavior = null;
  38689. }
  38690. },
  38691. enumerable: true,
  38692. configurable: true
  38693. });
  38694. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  38695. get: function () {
  38696. return this._framingBehavior;
  38697. },
  38698. enumerable: true,
  38699. configurable: true
  38700. });
  38701. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  38702. get: function () {
  38703. return this._framingBehavior != null;
  38704. },
  38705. set: function (value) {
  38706. if (value === this.useFramingBehavior) {
  38707. return;
  38708. }
  38709. if (value) {
  38710. this._framingBehavior = new BABYLON.FramingBehavior();
  38711. this.addBehavior(this._framingBehavior);
  38712. }
  38713. else if (this._framingBehavior) {
  38714. this.removeBehavior(this._framingBehavior);
  38715. this._framingBehavior = null;
  38716. }
  38717. },
  38718. enumerable: true,
  38719. configurable: true
  38720. });
  38721. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  38722. get: function () {
  38723. return this._autoRotationBehavior;
  38724. },
  38725. enumerable: true,
  38726. configurable: true
  38727. });
  38728. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  38729. get: function () {
  38730. return this._autoRotationBehavior != null;
  38731. },
  38732. set: function (value) {
  38733. if (value === this.useAutoRotationBehavior) {
  38734. return;
  38735. }
  38736. if (value) {
  38737. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  38738. this.addBehavior(this._autoRotationBehavior);
  38739. }
  38740. else if (this._autoRotationBehavior) {
  38741. this.removeBehavior(this._autoRotationBehavior);
  38742. this._autoRotationBehavior = null;
  38743. }
  38744. },
  38745. enumerable: true,
  38746. configurable: true
  38747. });
  38748. // Cache
  38749. ArcRotateCamera.prototype._initCache = function () {
  38750. _super.prototype._initCache.call(this);
  38751. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38752. this._cache.alpha = undefined;
  38753. this._cache.beta = undefined;
  38754. this._cache.radius = undefined;
  38755. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  38756. };
  38757. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  38758. if (!ignoreParentClass) {
  38759. _super.prototype._updateCache.call(this);
  38760. }
  38761. this._cache._target.copyFrom(this._getTargetPosition());
  38762. this._cache.alpha = this.alpha;
  38763. this._cache.beta = this.beta;
  38764. this._cache.radius = this.radius;
  38765. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  38766. };
  38767. ArcRotateCamera.prototype._getTargetPosition = function () {
  38768. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  38769. var pos = this._targetHost.getAbsolutePosition();
  38770. if (this._targetBoundingCenter) {
  38771. pos.addToRef(this._targetBoundingCenter, this._target);
  38772. }
  38773. else {
  38774. this._target.copyFrom(pos);
  38775. }
  38776. }
  38777. var lockedTargetPosition = this._getLockedTargetPosition();
  38778. if (lockedTargetPosition) {
  38779. return lockedTargetPosition;
  38780. }
  38781. return this._target;
  38782. };
  38783. ArcRotateCamera.prototype.storeState = function () {
  38784. this._storedAlpha = this.alpha;
  38785. this._storedBeta = this.beta;
  38786. this._storedRadius = this.radius;
  38787. this._storedTarget = this._getTargetPosition().clone();
  38788. return _super.prototype.storeState.call(this);
  38789. };
  38790. /**
  38791. * Restored camera state. You must call storeState() first
  38792. */
  38793. ArcRotateCamera.prototype._restoreStateValues = function () {
  38794. if (!_super.prototype._restoreStateValues.call(this)) {
  38795. return false;
  38796. }
  38797. this.alpha = this._storedAlpha;
  38798. this.beta = this._storedBeta;
  38799. this.radius = this._storedRadius;
  38800. this.setTarget(this._storedTarget.clone());
  38801. this.inertialAlphaOffset = 0;
  38802. this.inertialBetaOffset = 0;
  38803. this.inertialRadiusOffset = 0;
  38804. this.inertialPanningX = 0;
  38805. this.inertialPanningY = 0;
  38806. return true;
  38807. };
  38808. // Synchronized
  38809. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  38810. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  38811. return false;
  38812. return this._cache._target.equals(this._getTargetPosition())
  38813. && this._cache.alpha === this.alpha
  38814. && this._cache.beta === this.beta
  38815. && this._cache.radius === this.radius
  38816. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  38817. };
  38818. // Methods
  38819. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  38820. var _this = this;
  38821. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  38822. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  38823. this._useCtrlForPanning = useCtrlForPanning;
  38824. this._panningMouseButton = panningMouseButton;
  38825. this.inputs.attachElement(element, noPreventDefault);
  38826. this._reset = function () {
  38827. _this.inertialAlphaOffset = 0;
  38828. _this.inertialBetaOffset = 0;
  38829. _this.inertialRadiusOffset = 0;
  38830. _this.inertialPanningX = 0;
  38831. _this.inertialPanningY = 0;
  38832. };
  38833. };
  38834. ArcRotateCamera.prototype.detachControl = function (element) {
  38835. this.inputs.detachElement(element);
  38836. if (this._reset) {
  38837. this._reset();
  38838. }
  38839. };
  38840. ArcRotateCamera.prototype._checkInputs = function () {
  38841. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  38842. if (this._collisionTriggered) {
  38843. return;
  38844. }
  38845. this.inputs.checkInputs();
  38846. // Inertia
  38847. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  38848. if (this.getScene().useRightHandedSystem) {
  38849. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38850. }
  38851. else {
  38852. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38853. }
  38854. this.beta += this.inertialBetaOffset;
  38855. this.radius -= this.inertialRadiusOffset;
  38856. this.inertialAlphaOffset *= this.inertia;
  38857. this.inertialBetaOffset *= this.inertia;
  38858. this.inertialRadiusOffset *= this.inertia;
  38859. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  38860. this.inertialAlphaOffset = 0;
  38861. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  38862. this.inertialBetaOffset = 0;
  38863. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  38864. this.inertialRadiusOffset = 0;
  38865. }
  38866. // Panning inertia
  38867. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  38868. if (!this._localDirection) {
  38869. this._localDirection = BABYLON.Vector3.Zero();
  38870. this._transformedDirection = BABYLON.Vector3.Zero();
  38871. }
  38872. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  38873. this._localDirection.multiplyInPlace(this.panningAxis);
  38874. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  38875. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  38876. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  38877. if (!this.panningAxis.y) {
  38878. this._transformedDirection.y = 0;
  38879. }
  38880. if (!this._targetHost) {
  38881. if (this.panningDistanceLimit) {
  38882. this._transformedDirection.addInPlace(this._target);
  38883. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  38884. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  38885. this._target.copyFrom(this._transformedDirection);
  38886. }
  38887. }
  38888. else {
  38889. this._target.addInPlace(this._transformedDirection);
  38890. }
  38891. }
  38892. this.inertialPanningX *= this.panningInertia;
  38893. this.inertialPanningY *= this.panningInertia;
  38894. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  38895. this.inertialPanningX = 0;
  38896. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  38897. this.inertialPanningY = 0;
  38898. }
  38899. // Limits
  38900. this._checkLimits();
  38901. _super.prototype._checkInputs.call(this);
  38902. };
  38903. ArcRotateCamera.prototype._checkLimits = function () {
  38904. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  38905. if (this.allowUpsideDown && this.beta > Math.PI) {
  38906. this.beta = this.beta - (2 * Math.PI);
  38907. }
  38908. }
  38909. else {
  38910. if (this.beta < this.lowerBetaLimit) {
  38911. this.beta = this.lowerBetaLimit;
  38912. }
  38913. }
  38914. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  38915. if (this.allowUpsideDown && this.beta < -Math.PI) {
  38916. this.beta = this.beta + (2 * Math.PI);
  38917. }
  38918. }
  38919. else {
  38920. if (this.beta > this.upperBetaLimit) {
  38921. this.beta = this.upperBetaLimit;
  38922. }
  38923. }
  38924. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  38925. this.alpha = this.lowerAlphaLimit;
  38926. }
  38927. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  38928. this.alpha = this.upperAlphaLimit;
  38929. }
  38930. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  38931. this.radius = this.lowerRadiusLimit;
  38932. }
  38933. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  38934. this.radius = this.upperRadiusLimit;
  38935. }
  38936. };
  38937. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  38938. var radiusv3 = this.position.subtract(this._getTargetPosition());
  38939. this.radius = radiusv3.length();
  38940. if (this.radius === 0) {
  38941. this.radius = 0.0001; // Just to avoid division by zero
  38942. }
  38943. // Alpha
  38944. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  38945. if (radiusv3.z < 0) {
  38946. this.alpha = 2 * Math.PI - this.alpha;
  38947. }
  38948. // Beta
  38949. this.beta = Math.acos(radiusv3.y / this.radius);
  38950. this._checkLimits();
  38951. };
  38952. ArcRotateCamera.prototype.setPosition = function (position) {
  38953. if (this.position.equals(position)) {
  38954. return;
  38955. }
  38956. this.position.copyFrom(position);
  38957. this.rebuildAnglesAndRadius();
  38958. };
  38959. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  38960. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  38961. if (allowSamePosition === void 0) { allowSamePosition = false; }
  38962. if (target.getBoundingInfo) {
  38963. if (toBoundingCenter) {
  38964. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  38965. }
  38966. else {
  38967. this._targetBoundingCenter = null;
  38968. }
  38969. this._targetHost = target;
  38970. this._target = this._getTargetPosition();
  38971. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  38972. }
  38973. else {
  38974. var newTarget = target;
  38975. var currentTarget = this._getTargetPosition();
  38976. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  38977. return;
  38978. }
  38979. this._targetHost = null;
  38980. this._target = newTarget;
  38981. this._targetBoundingCenter = null;
  38982. this.onMeshTargetChangedObservable.notifyObservers(null);
  38983. }
  38984. this.rebuildAnglesAndRadius();
  38985. };
  38986. ArcRotateCamera.prototype._getViewMatrix = function () {
  38987. // Compute
  38988. var cosa = Math.cos(this.alpha);
  38989. var sina = Math.sin(this.alpha);
  38990. var cosb = Math.cos(this.beta);
  38991. var sinb = Math.sin(this.beta);
  38992. if (sinb === 0) {
  38993. sinb = 0.0001;
  38994. }
  38995. var target = this._getTargetPosition();
  38996. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  38997. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  38998. if (!this._collider) {
  38999. this._collider = new BABYLON.Collider();
  39000. }
  39001. this._collider.radius = this.collisionRadius;
  39002. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  39003. this._collisionTriggered = true;
  39004. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39005. }
  39006. else {
  39007. this.position.copyFrom(this._newPosition);
  39008. var up = this.upVector;
  39009. if (this.allowUpsideDown && sinb < 0) {
  39010. up = up.clone();
  39011. up = up.negate();
  39012. }
  39013. if (this.getScene().useRightHandedSystem) {
  39014. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  39015. }
  39016. else {
  39017. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  39018. }
  39019. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  39020. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  39021. }
  39022. this._currentTarget = target;
  39023. return this._viewMatrix;
  39024. };
  39025. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  39026. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39027. meshes = meshes || this.getScene().meshes;
  39028. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  39029. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  39030. this.radius = distance * this.zoomOnFactor;
  39031. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  39032. };
  39033. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  39034. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39035. var meshesOrMinMaxVector;
  39036. var distance;
  39037. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  39038. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  39039. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  39040. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  39041. }
  39042. else {
  39043. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  39044. meshesOrMinMaxVector = minMaxVectorAndDistance;
  39045. distance = minMaxVectorAndDistance.distance;
  39046. }
  39047. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  39048. if (!doNotUpdateMaxZ) {
  39049. this.maxZ = distance * 2;
  39050. }
  39051. };
  39052. /**
  39053. * @override
  39054. * Override Camera.createRigCamera
  39055. */
  39056. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39057. var alphaShift = 0;
  39058. switch (this.cameraRigMode) {
  39059. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39060. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39061. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39062. case BABYLON.Camera.RIG_MODE_VR:
  39063. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  39064. break;
  39065. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39066. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  39067. break;
  39068. }
  39069. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  39070. rigCam._cameraRigParams = {};
  39071. return rigCam;
  39072. };
  39073. /**
  39074. * @override
  39075. * Override Camera._updateRigCameras
  39076. */
  39077. ArcRotateCamera.prototype._updateRigCameras = function () {
  39078. var camLeft = this._rigCameras[0];
  39079. var camRight = this._rigCameras[1];
  39080. camLeft.beta = camRight.beta = this.beta;
  39081. camLeft.radius = camRight.radius = this.radius;
  39082. switch (this.cameraRigMode) {
  39083. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39084. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39085. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39086. case BABYLON.Camera.RIG_MODE_VR:
  39087. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39088. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39089. break;
  39090. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39091. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39092. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39093. break;
  39094. }
  39095. _super.prototype._updateRigCameras.call(this);
  39096. };
  39097. ArcRotateCamera.prototype.dispose = function () {
  39098. this.inputs.clear();
  39099. _super.prototype.dispose.call(this);
  39100. };
  39101. ArcRotateCamera.prototype.getClassName = function () {
  39102. return "ArcRotateCamera";
  39103. };
  39104. __decorate([
  39105. BABYLON.serialize()
  39106. ], ArcRotateCamera.prototype, "alpha", void 0);
  39107. __decorate([
  39108. BABYLON.serialize()
  39109. ], ArcRotateCamera.prototype, "beta", void 0);
  39110. __decorate([
  39111. BABYLON.serialize()
  39112. ], ArcRotateCamera.prototype, "radius", void 0);
  39113. __decorate([
  39114. BABYLON.serializeAsVector3("target")
  39115. ], ArcRotateCamera.prototype, "_target", void 0);
  39116. __decorate([
  39117. BABYLON.serialize()
  39118. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39119. __decorate([
  39120. BABYLON.serialize()
  39121. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39122. __decorate([
  39123. BABYLON.serialize()
  39124. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39125. __decorate([
  39126. BABYLON.serialize()
  39127. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39128. __decorate([
  39129. BABYLON.serialize()
  39130. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39131. __decorate([
  39132. BABYLON.serialize()
  39133. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39134. __decorate([
  39135. BABYLON.serialize()
  39136. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39137. __decorate([
  39138. BABYLON.serialize()
  39139. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39140. __decorate([
  39141. BABYLON.serialize()
  39142. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39143. __decorate([
  39144. BABYLON.serialize()
  39145. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39146. __decorate([
  39147. BABYLON.serialize()
  39148. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  39149. __decorate([
  39150. BABYLON.serialize()
  39151. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39152. __decorate([
  39153. BABYLON.serialize()
  39154. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39155. __decorate([
  39156. BABYLON.serializeAsVector3()
  39157. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39158. __decorate([
  39159. BABYLON.serialize()
  39160. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39161. __decorate([
  39162. BABYLON.serialize()
  39163. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39164. __decorate([
  39165. BABYLON.serialize()
  39166. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39167. return ArcRotateCamera;
  39168. }(BABYLON.TargetCamera));
  39169. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39170. })(BABYLON || (BABYLON = {}));
  39171. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39172. var BABYLON;
  39173. (function (BABYLON) {
  39174. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39175. __extends(ArcRotateCameraInputsManager, _super);
  39176. function ArcRotateCameraInputsManager(camera) {
  39177. return _super.call(this, camera) || this;
  39178. }
  39179. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39180. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39181. return this;
  39182. };
  39183. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39184. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39185. return this;
  39186. };
  39187. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39188. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39189. return this;
  39190. };
  39191. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39192. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39193. return this;
  39194. };
  39195. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39196. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39197. return this;
  39198. };
  39199. return ArcRotateCameraInputsManager;
  39200. }(BABYLON.CameraInputsManager));
  39201. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39202. })(BABYLON || (BABYLON = {}));
  39203. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39204. var BABYLON;
  39205. (function (BABYLON) {
  39206. var HemisphericLight = /** @class */ (function (_super) {
  39207. __extends(HemisphericLight, _super);
  39208. /**
  39209. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39210. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39211. * The HemisphericLight can't cast shadows.
  39212. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39213. */
  39214. function HemisphericLight(name, direction, scene) {
  39215. var _this = _super.call(this, name, scene) || this;
  39216. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39217. _this.direction = direction || BABYLON.Vector3.Up();
  39218. return _this;
  39219. }
  39220. HemisphericLight.prototype._buildUniformLayout = function () {
  39221. this._uniformBuffer.addUniform("vLightData", 4);
  39222. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39223. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39224. this._uniformBuffer.addUniform("vLightGround", 3);
  39225. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39226. this._uniformBuffer.addUniform("depthValues", 2);
  39227. this._uniformBuffer.create();
  39228. };
  39229. /**
  39230. * Returns the string "HemisphericLight".
  39231. */
  39232. HemisphericLight.prototype.getClassName = function () {
  39233. return "HemisphericLight";
  39234. };
  39235. /**
  39236. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39237. * Returns the updated direction.
  39238. */
  39239. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39240. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39241. return this.direction;
  39242. };
  39243. HemisphericLight.prototype.getShadowGenerator = function () {
  39244. return null;
  39245. };
  39246. /**
  39247. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39248. * Returns the HemisphericLight.
  39249. */
  39250. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39251. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39252. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39253. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39254. return this;
  39255. };
  39256. HemisphericLight.prototype._getWorldMatrix = function () {
  39257. if (!this._worldMatrix) {
  39258. this._worldMatrix = BABYLON.Matrix.Identity();
  39259. }
  39260. return this._worldMatrix;
  39261. };
  39262. /**
  39263. * Returns the integer 3.
  39264. */
  39265. HemisphericLight.prototype.getTypeID = function () {
  39266. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39267. };
  39268. __decorate([
  39269. BABYLON.serializeAsColor3()
  39270. ], HemisphericLight.prototype, "groundColor", void 0);
  39271. __decorate([
  39272. BABYLON.serializeAsVector3()
  39273. ], HemisphericLight.prototype, "direction", void 0);
  39274. return HemisphericLight;
  39275. }(BABYLON.Light));
  39276. BABYLON.HemisphericLight = HemisphericLight;
  39277. })(BABYLON || (BABYLON = {}));
  39278. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39279. var BABYLON;
  39280. (function (BABYLON) {
  39281. var ShadowLight = /** @class */ (function (_super) {
  39282. __extends(ShadowLight, _super);
  39283. function ShadowLight() {
  39284. var _this = _super !== null && _super.apply(this, arguments) || this;
  39285. _this._needProjectionMatrixCompute = true;
  39286. return _this;
  39287. }
  39288. Object.defineProperty(ShadowLight.prototype, "direction", {
  39289. get: function () {
  39290. return this._direction;
  39291. },
  39292. set: function (value) {
  39293. this._direction = value;
  39294. },
  39295. enumerable: true,
  39296. configurable: true
  39297. });
  39298. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39299. get: function () {
  39300. return this._shadowMinZ;
  39301. },
  39302. set: function (value) {
  39303. this._shadowMinZ = value;
  39304. this.forceProjectionMatrixCompute();
  39305. },
  39306. enumerable: true,
  39307. configurable: true
  39308. });
  39309. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39310. get: function () {
  39311. return this._shadowMaxZ;
  39312. },
  39313. set: function (value) {
  39314. this._shadowMaxZ = value;
  39315. this.forceProjectionMatrixCompute();
  39316. },
  39317. enumerable: true,
  39318. configurable: true
  39319. });
  39320. /**
  39321. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  39322. */
  39323. ShadowLight.prototype.computeTransformedInformation = function () {
  39324. if (this.parent && this.parent.getWorldMatrix) {
  39325. if (!this.transformedPosition) {
  39326. this.transformedPosition = BABYLON.Vector3.Zero();
  39327. }
  39328. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39329. // In case the direction is present.
  39330. if (this.direction) {
  39331. if (!this.transformedDirection) {
  39332. this.transformedDirection = BABYLON.Vector3.Zero();
  39333. }
  39334. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39335. }
  39336. return true;
  39337. }
  39338. return false;
  39339. };
  39340. /**
  39341. * Return the depth scale used for the shadow map.
  39342. */
  39343. ShadowLight.prototype.getDepthScale = function () {
  39344. return 50.0;
  39345. };
  39346. /**
  39347. * Returns the light direction (Vector3) for any passed face index.
  39348. */
  39349. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39350. return this.transformedDirection ? this.transformedDirection : this.direction;
  39351. };
  39352. /**
  39353. * Returns the DirectionalLight absolute position in the World.
  39354. */
  39355. ShadowLight.prototype.getAbsolutePosition = function () {
  39356. return this.transformedPosition ? this.transformedPosition : this.position;
  39357. };
  39358. /**
  39359. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39360. * Returns the updated DirectionalLight direction (Vector3).
  39361. */
  39362. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39363. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39364. return this.direction;
  39365. };
  39366. /**
  39367. * Returns the light rotation (Vector3).
  39368. */
  39369. ShadowLight.prototype.getRotation = function () {
  39370. this.direction.normalize();
  39371. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  39372. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  39373. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  39374. };
  39375. /**
  39376. * Boolean : false by default.
  39377. */
  39378. ShadowLight.prototype.needCube = function () {
  39379. return false;
  39380. };
  39381. /**
  39382. * Specifies wether or not the projection matrix should be recomputed this frame.
  39383. */
  39384. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  39385. return this._needProjectionMatrixCompute;
  39386. };
  39387. /**
  39388. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  39389. */
  39390. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  39391. this._needProjectionMatrixCompute = true;
  39392. };
  39393. /**
  39394. * Get the world matrix of the sahdow lights.
  39395. */
  39396. ShadowLight.prototype._getWorldMatrix = function () {
  39397. if (!this._worldMatrix) {
  39398. this._worldMatrix = BABYLON.Matrix.Identity();
  39399. }
  39400. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  39401. return this._worldMatrix;
  39402. };
  39403. /**
  39404. * Gets the minZ used for shadow according to both the scene and the light.
  39405. * @param activeCamera
  39406. */
  39407. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  39408. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  39409. };
  39410. /**
  39411. * Gets the maxZ used for shadow according to both the scene and the light.
  39412. * @param activeCamera
  39413. */
  39414. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  39415. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  39416. };
  39417. /**
  39418. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  39419. * Returns the light.
  39420. */
  39421. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39422. if (this.customProjectionMatrixBuilder) {
  39423. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  39424. }
  39425. else {
  39426. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39427. }
  39428. return this;
  39429. };
  39430. __decorate([
  39431. BABYLON.serializeAsVector3()
  39432. ], ShadowLight.prototype, "position", void 0);
  39433. __decorate([
  39434. BABYLON.serializeAsVector3()
  39435. ], ShadowLight.prototype, "direction", null);
  39436. __decorate([
  39437. BABYLON.serialize()
  39438. ], ShadowLight.prototype, "shadowMinZ", null);
  39439. __decorate([
  39440. BABYLON.serialize()
  39441. ], ShadowLight.prototype, "shadowMaxZ", null);
  39442. return ShadowLight;
  39443. }(BABYLON.Light));
  39444. BABYLON.ShadowLight = ShadowLight;
  39445. })(BABYLON || (BABYLON = {}));
  39446. //# sourceMappingURL=babylon.shadowLight.js.map
  39447. var BABYLON;
  39448. (function (BABYLON) {
  39449. var PointLight = /** @class */ (function (_super) {
  39450. __extends(PointLight, _super);
  39451. /**
  39452. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  39453. * A PointLight emits the light in every direction.
  39454. * It can cast shadows.
  39455. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  39456. * ```javascript
  39457. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  39458. * ```
  39459. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39460. */
  39461. function PointLight(name, position, scene) {
  39462. var _this = _super.call(this, name, scene) || this;
  39463. _this._shadowAngle = Math.PI / 2;
  39464. _this.position = position;
  39465. return _this;
  39466. }
  39467. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  39468. /**
  39469. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39470. * This specifies what angle the shadow will use to be created.
  39471. *
  39472. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39473. */
  39474. get: function () {
  39475. return this._shadowAngle;
  39476. },
  39477. /**
  39478. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39479. * This specifies what angle the shadow will use to be created.
  39480. *
  39481. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39482. */
  39483. set: function (value) {
  39484. this._shadowAngle = value;
  39485. this.forceProjectionMatrixCompute();
  39486. },
  39487. enumerable: true,
  39488. configurable: true
  39489. });
  39490. Object.defineProperty(PointLight.prototype, "direction", {
  39491. get: function () {
  39492. return this._direction;
  39493. },
  39494. /**
  39495. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39496. */
  39497. set: function (value) {
  39498. var previousNeedCube = this.needCube();
  39499. this._direction = value;
  39500. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  39501. this._shadowGenerator.recreateShadowMap();
  39502. }
  39503. },
  39504. enumerable: true,
  39505. configurable: true
  39506. });
  39507. /**
  39508. * Returns the string "PointLight"
  39509. */
  39510. PointLight.prototype.getClassName = function () {
  39511. return "PointLight";
  39512. };
  39513. /**
  39514. * Returns the integer 0.
  39515. */
  39516. PointLight.prototype.getTypeID = function () {
  39517. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  39518. };
  39519. /**
  39520. * Specifies wether or not the shadowmap should be a cube texture.
  39521. */
  39522. PointLight.prototype.needCube = function () {
  39523. return !this.direction;
  39524. };
  39525. /**
  39526. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  39527. */
  39528. PointLight.prototype.getShadowDirection = function (faceIndex) {
  39529. if (this.direction) {
  39530. return _super.prototype.getShadowDirection.call(this, faceIndex);
  39531. }
  39532. else {
  39533. switch (faceIndex) {
  39534. case 0:
  39535. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  39536. case 1:
  39537. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  39538. case 2:
  39539. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  39540. case 3:
  39541. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  39542. case 4:
  39543. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  39544. case 5:
  39545. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  39546. }
  39547. }
  39548. return BABYLON.Vector3.Zero();
  39549. };
  39550. /**
  39551. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  39552. * - fov = PI / 2
  39553. * - aspect ratio : 1.0
  39554. * - z-near and far equal to the active camera minZ and maxZ.
  39555. * Returns the PointLight.
  39556. */
  39557. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39558. var activeCamera = this.getScene().activeCamera;
  39559. if (!activeCamera) {
  39560. return;
  39561. }
  39562. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39563. };
  39564. PointLight.prototype._buildUniformLayout = function () {
  39565. this._uniformBuffer.addUniform("vLightData", 4);
  39566. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39567. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39568. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39569. this._uniformBuffer.addUniform("depthValues", 2);
  39570. this._uniformBuffer.create();
  39571. };
  39572. /**
  39573. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  39574. * Returns the PointLight.
  39575. */
  39576. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  39577. if (this.computeTransformedInformation()) {
  39578. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  39579. return this;
  39580. }
  39581. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  39582. return this;
  39583. };
  39584. __decorate([
  39585. BABYLON.serialize()
  39586. ], PointLight.prototype, "shadowAngle", null);
  39587. return PointLight;
  39588. }(BABYLON.ShadowLight));
  39589. BABYLON.PointLight = PointLight;
  39590. })(BABYLON || (BABYLON = {}));
  39591. //# sourceMappingURL=babylon.pointLight.js.map
  39592. var BABYLON;
  39593. (function (BABYLON) {
  39594. var DirectionalLight = /** @class */ (function (_super) {
  39595. __extends(DirectionalLight, _super);
  39596. /**
  39597. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  39598. * The directional light is emitted from everywhere in the given direction.
  39599. * It can cast shawdows.
  39600. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39601. */
  39602. function DirectionalLight(name, direction, scene) {
  39603. var _this = _super.call(this, name, scene) || this;
  39604. _this._shadowFrustumSize = 0;
  39605. _this._shadowOrthoScale = 0.5;
  39606. _this.autoUpdateExtends = true;
  39607. // Cache
  39608. _this._orthoLeft = Number.MAX_VALUE;
  39609. _this._orthoRight = Number.MIN_VALUE;
  39610. _this._orthoTop = Number.MIN_VALUE;
  39611. _this._orthoBottom = Number.MAX_VALUE;
  39612. _this.position = direction.scale(-1.0);
  39613. _this.direction = direction;
  39614. return _this;
  39615. }
  39616. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  39617. /**
  39618. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  39619. */
  39620. get: function () {
  39621. return this._shadowFrustumSize;
  39622. },
  39623. /**
  39624. * Specifies a fix frustum size for the shadow generation.
  39625. */
  39626. set: function (value) {
  39627. this._shadowFrustumSize = value;
  39628. this.forceProjectionMatrixCompute();
  39629. },
  39630. enumerable: true,
  39631. configurable: true
  39632. });
  39633. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  39634. get: function () {
  39635. return this._shadowOrthoScale;
  39636. },
  39637. set: function (value) {
  39638. this._shadowOrthoScale = value;
  39639. this.forceProjectionMatrixCompute();
  39640. },
  39641. enumerable: true,
  39642. configurable: true
  39643. });
  39644. /**
  39645. * Returns the string "DirectionalLight".
  39646. */
  39647. DirectionalLight.prototype.getClassName = function () {
  39648. return "DirectionalLight";
  39649. };
  39650. /**
  39651. * Returns the integer 1.
  39652. */
  39653. DirectionalLight.prototype.getTypeID = function () {
  39654. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  39655. };
  39656. /**
  39657. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  39658. * Returns the DirectionalLight Shadow projection matrix.
  39659. */
  39660. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39661. if (this.shadowFrustumSize > 0) {
  39662. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  39663. }
  39664. else {
  39665. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39666. }
  39667. };
  39668. /**
  39669. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  39670. * Returns the DirectionalLight Shadow projection matrix.
  39671. */
  39672. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  39673. var activeCamera = this.getScene().activeCamera;
  39674. if (!activeCamera) {
  39675. return;
  39676. }
  39677. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  39678. };
  39679. /**
  39680. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  39681. * Returns the DirectionalLight Shadow projection matrix.
  39682. */
  39683. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39684. var activeCamera = this.getScene().activeCamera;
  39685. if (!activeCamera) {
  39686. return;
  39687. }
  39688. // Check extends
  39689. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  39690. var tempVector3 = BABYLON.Vector3.Zero();
  39691. this._orthoLeft = Number.MAX_VALUE;
  39692. this._orthoRight = Number.MIN_VALUE;
  39693. this._orthoTop = Number.MIN_VALUE;
  39694. this._orthoBottom = Number.MAX_VALUE;
  39695. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  39696. var mesh = renderList[meshIndex];
  39697. if (!mesh) {
  39698. continue;
  39699. }
  39700. var boundingInfo = mesh.getBoundingInfo();
  39701. if (!boundingInfo) {
  39702. continue;
  39703. }
  39704. var boundingBox = boundingInfo.boundingBox;
  39705. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  39706. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  39707. if (tempVector3.x < this._orthoLeft)
  39708. this._orthoLeft = tempVector3.x;
  39709. if (tempVector3.y < this._orthoBottom)
  39710. this._orthoBottom = tempVector3.y;
  39711. if (tempVector3.x > this._orthoRight)
  39712. this._orthoRight = tempVector3.x;
  39713. if (tempVector3.y > this._orthoTop)
  39714. this._orthoTop = tempVector3.y;
  39715. }
  39716. }
  39717. }
  39718. var xOffset = this._orthoRight - this._orthoLeft;
  39719. var yOffset = this._orthoTop - this._orthoBottom;
  39720. 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);
  39721. };
  39722. DirectionalLight.prototype._buildUniformLayout = function () {
  39723. this._uniformBuffer.addUniform("vLightData", 4);
  39724. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39725. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39726. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39727. this._uniformBuffer.addUniform("depthValues", 2);
  39728. this._uniformBuffer.create();
  39729. };
  39730. /**
  39731. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  39732. * Returns the DirectionalLight.
  39733. */
  39734. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  39735. if (this.computeTransformedInformation()) {
  39736. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  39737. return this;
  39738. }
  39739. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  39740. return this;
  39741. };
  39742. /**
  39743. * Gets the minZ used for shadow according to both the scene and the light.
  39744. *
  39745. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39746. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39747. * @param activeCamera
  39748. */
  39749. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  39750. return 1;
  39751. };
  39752. /**
  39753. * Gets the maxZ used for shadow according to both the scene and the light.
  39754. *
  39755. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39756. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39757. * @param activeCamera
  39758. */
  39759. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  39760. return 1;
  39761. };
  39762. __decorate([
  39763. BABYLON.serialize()
  39764. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  39765. __decorate([
  39766. BABYLON.serialize()
  39767. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  39768. __decorate([
  39769. BABYLON.serialize()
  39770. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  39771. return DirectionalLight;
  39772. }(BABYLON.ShadowLight));
  39773. BABYLON.DirectionalLight = DirectionalLight;
  39774. })(BABYLON || (BABYLON = {}));
  39775. //# sourceMappingURL=babylon.directionalLight.js.map
  39776. var BABYLON;
  39777. (function (BABYLON) {
  39778. var SpotLight = /** @class */ (function (_super) {
  39779. __extends(SpotLight, _super);
  39780. /**
  39781. * Creates a SpotLight object in the scene with the passed parameters :
  39782. * - `position` (Vector3) is the initial SpotLight position,
  39783. * - `direction` (Vector3) is the initial SpotLight direction,
  39784. * - `angle` (float, in radians) is the spot light cone angle,
  39785. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  39786. * A spot light is a simply light oriented cone.
  39787. * It can cast shadows.
  39788. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39789. */
  39790. function SpotLight(name, position, direction, angle, exponent, scene) {
  39791. var _this = _super.call(this, name, scene) || this;
  39792. _this.position = position;
  39793. _this.direction = direction;
  39794. _this.angle = angle;
  39795. _this.exponent = exponent;
  39796. return _this;
  39797. }
  39798. Object.defineProperty(SpotLight.prototype, "angle", {
  39799. get: function () {
  39800. return this._angle;
  39801. },
  39802. set: function (value) {
  39803. this._angle = value;
  39804. this.forceProjectionMatrixCompute();
  39805. },
  39806. enumerable: true,
  39807. configurable: true
  39808. });
  39809. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  39810. get: function () {
  39811. return this._shadowAngleScale;
  39812. },
  39813. /**
  39814. * Allows scaling the angle of the light for shadow generation only.
  39815. */
  39816. set: function (value) {
  39817. this._shadowAngleScale = value;
  39818. this.forceProjectionMatrixCompute();
  39819. },
  39820. enumerable: true,
  39821. configurable: true
  39822. });
  39823. /**
  39824. * Returns the string "SpotLight".
  39825. */
  39826. SpotLight.prototype.getClassName = function () {
  39827. return "SpotLight";
  39828. };
  39829. /**
  39830. * Returns the integer 2.
  39831. */
  39832. SpotLight.prototype.getTypeID = function () {
  39833. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  39834. };
  39835. /**
  39836. * 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.
  39837. * Returns the SpotLight.
  39838. */
  39839. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39840. var activeCamera = this.getScene().activeCamera;
  39841. if (!activeCamera) {
  39842. return;
  39843. }
  39844. this._shadowAngleScale = this._shadowAngleScale || 1;
  39845. var angle = this._shadowAngleScale * this._angle;
  39846. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39847. };
  39848. SpotLight.prototype._buildUniformLayout = function () {
  39849. this._uniformBuffer.addUniform("vLightData", 4);
  39850. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39851. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39852. this._uniformBuffer.addUniform("vLightDirection", 3);
  39853. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39854. this._uniformBuffer.addUniform("depthValues", 2);
  39855. this._uniformBuffer.create();
  39856. };
  39857. /**
  39858. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  39859. * Return the SpotLight.
  39860. */
  39861. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  39862. var normalizeDirection;
  39863. if (this.computeTransformedInformation()) {
  39864. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  39865. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  39866. }
  39867. else {
  39868. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  39869. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39870. }
  39871. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  39872. return this;
  39873. };
  39874. __decorate([
  39875. BABYLON.serialize()
  39876. ], SpotLight.prototype, "angle", null);
  39877. __decorate([
  39878. BABYLON.serialize()
  39879. /**
  39880. * Allows scaling the angle of the light for shadow generation only.
  39881. */
  39882. ], SpotLight.prototype, "shadowAngleScale", null);
  39883. __decorate([
  39884. BABYLON.serialize()
  39885. ], SpotLight.prototype, "exponent", void 0);
  39886. return SpotLight;
  39887. }(BABYLON.ShadowLight));
  39888. BABYLON.SpotLight = SpotLight;
  39889. })(BABYLON || (BABYLON = {}));
  39890. //# sourceMappingURL=babylon.spotLight.js.map
  39891. var BABYLON;
  39892. (function (BABYLON) {
  39893. var AnimationRange = /** @class */ (function () {
  39894. function AnimationRange(name, from, to) {
  39895. this.name = name;
  39896. this.from = from;
  39897. this.to = to;
  39898. }
  39899. AnimationRange.prototype.clone = function () {
  39900. return new AnimationRange(this.name, this.from, this.to);
  39901. };
  39902. return AnimationRange;
  39903. }());
  39904. BABYLON.AnimationRange = AnimationRange;
  39905. /**
  39906. * Composed of a frame, and an action function
  39907. */
  39908. var AnimationEvent = /** @class */ (function () {
  39909. function AnimationEvent(frame, action, onlyOnce) {
  39910. this.frame = frame;
  39911. this.action = action;
  39912. this.onlyOnce = onlyOnce;
  39913. this.isDone = false;
  39914. }
  39915. return AnimationEvent;
  39916. }());
  39917. BABYLON.AnimationEvent = AnimationEvent;
  39918. var PathCursor = /** @class */ (function () {
  39919. function PathCursor(path) {
  39920. this.path = path;
  39921. this._onchange = new Array();
  39922. this.value = 0;
  39923. this.animations = new Array();
  39924. }
  39925. PathCursor.prototype.getPoint = function () {
  39926. var point = this.path.getPointAtLengthPosition(this.value);
  39927. return new BABYLON.Vector3(point.x, 0, point.y);
  39928. };
  39929. PathCursor.prototype.moveAhead = function (step) {
  39930. if (step === void 0) { step = 0.002; }
  39931. this.move(step);
  39932. return this;
  39933. };
  39934. PathCursor.prototype.moveBack = function (step) {
  39935. if (step === void 0) { step = 0.002; }
  39936. this.move(-step);
  39937. return this;
  39938. };
  39939. PathCursor.prototype.move = function (step) {
  39940. if (Math.abs(step) > 1) {
  39941. throw "step size should be less than 1.";
  39942. }
  39943. this.value += step;
  39944. this.ensureLimits();
  39945. this.raiseOnChange();
  39946. return this;
  39947. };
  39948. PathCursor.prototype.ensureLimits = function () {
  39949. while (this.value > 1) {
  39950. this.value -= 1;
  39951. }
  39952. while (this.value < 0) {
  39953. this.value += 1;
  39954. }
  39955. return this;
  39956. };
  39957. // used by animation engine
  39958. PathCursor.prototype.raiseOnChange = function () {
  39959. var _this = this;
  39960. this._onchange.forEach(function (f) { return f(_this); });
  39961. return this;
  39962. };
  39963. PathCursor.prototype.onchange = function (f) {
  39964. this._onchange.push(f);
  39965. return this;
  39966. };
  39967. return PathCursor;
  39968. }());
  39969. BABYLON.PathCursor = PathCursor;
  39970. var Animation = /** @class */ (function () {
  39971. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  39972. this.name = name;
  39973. this.targetProperty = targetProperty;
  39974. this.framePerSecond = framePerSecond;
  39975. this.dataType = dataType;
  39976. this.loopMode = loopMode;
  39977. this.enableBlending = enableBlending;
  39978. this._runtimeAnimations = new Array();
  39979. // The set of event that will be linked to this animation
  39980. this._events = new Array();
  39981. this.blendingSpeed = 0.01;
  39982. this._ranges = {};
  39983. this.targetPropertyPath = targetProperty.split(".");
  39984. this.dataType = dataType;
  39985. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  39986. }
  39987. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  39988. var dataType = undefined;
  39989. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  39990. dataType = Animation.ANIMATIONTYPE_FLOAT;
  39991. }
  39992. else if (from instanceof BABYLON.Quaternion) {
  39993. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  39994. }
  39995. else if (from instanceof BABYLON.Vector3) {
  39996. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  39997. }
  39998. else if (from instanceof BABYLON.Vector2) {
  39999. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  40000. }
  40001. else if (from instanceof BABYLON.Color3) {
  40002. dataType = Animation.ANIMATIONTYPE_COLOR3;
  40003. }
  40004. else if (from instanceof BABYLON.Size) {
  40005. dataType = Animation.ANIMATIONTYPE_SIZE;
  40006. }
  40007. if (dataType == undefined) {
  40008. return null;
  40009. }
  40010. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  40011. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  40012. animation.setKeys(keys);
  40013. if (easingFunction !== undefined) {
  40014. animation.setEasingFunction(easingFunction);
  40015. }
  40016. return animation;
  40017. };
  40018. /**
  40019. * Sets up an animation.
  40020. * @param property the property to animate
  40021. * @param animationType the animation type to apply
  40022. * @param easingFunction the easing function used in the animation
  40023. * @returns The created animation
  40024. */
  40025. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  40026. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40027. animation.setEasingFunction(easingFunction);
  40028. return animation;
  40029. };
  40030. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40031. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40032. if (!animation) {
  40033. return null;
  40034. }
  40035. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40036. };
  40037. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40038. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40039. if (!animation) {
  40040. return null;
  40041. }
  40042. node.animations.push(animation);
  40043. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40044. };
  40045. /**
  40046. * Transition property of the Camera to the target Value.
  40047. * @param property The property to transition
  40048. * @param targetValue The target Value of the property
  40049. * @param host The object where the property to animate belongs
  40050. * @param scene Scene used to run the animation
  40051. * @param frameRate Framerate (in frame/s) to use
  40052. * @param transition The transition type we want to use
  40053. * @param duration The duration of the animation, in milliseconds
  40054. * @param onAnimationEnd Call back trigger at the end of the animation.
  40055. */
  40056. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  40057. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  40058. if (duration <= 0) {
  40059. host[property] = targetValue;
  40060. if (onAnimationEnd) {
  40061. onAnimationEnd();
  40062. }
  40063. return null;
  40064. }
  40065. var endFrame = frameRate * (duration / 1000);
  40066. transition.setKeys([{
  40067. frame: 0,
  40068. value: host[property].clone ? host[property].clone() : host[property]
  40069. },
  40070. {
  40071. frame: endFrame,
  40072. value: targetValue
  40073. }]);
  40074. if (!host.animations) {
  40075. host.animations = [];
  40076. }
  40077. host.animations.push(transition);
  40078. var animation = scene.beginAnimation(host, 0, endFrame, false);
  40079. animation.onAnimationEnd = onAnimationEnd;
  40080. return animation;
  40081. };
  40082. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  40083. /**
  40084. * Return the array of runtime animations currently using this animation
  40085. */
  40086. get: function () {
  40087. return this._runtimeAnimations;
  40088. },
  40089. enumerable: true,
  40090. configurable: true
  40091. });
  40092. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40093. get: function () {
  40094. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40095. var runtimeAnimation = _a[_i];
  40096. if (!runtimeAnimation.isStopped) {
  40097. return true;
  40098. }
  40099. }
  40100. return false;
  40101. },
  40102. enumerable: true,
  40103. configurable: true
  40104. });
  40105. // Methods
  40106. /**
  40107. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40108. */
  40109. Animation.prototype.toString = function (fullDetails) {
  40110. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40111. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40112. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40113. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40114. if (fullDetails) {
  40115. ret += ", Ranges: {";
  40116. var first = true;
  40117. for (var name in this._ranges) {
  40118. if (first) {
  40119. ret += ", ";
  40120. first = false;
  40121. }
  40122. ret += name;
  40123. }
  40124. ret += "}";
  40125. }
  40126. return ret;
  40127. };
  40128. /**
  40129. * Add an event to this animation.
  40130. */
  40131. Animation.prototype.addEvent = function (event) {
  40132. this._events.push(event);
  40133. };
  40134. /**
  40135. * Remove all events found at the given frame
  40136. * @param frame
  40137. */
  40138. Animation.prototype.removeEvents = function (frame) {
  40139. for (var index = 0; index < this._events.length; index++) {
  40140. if (this._events[index].frame === frame) {
  40141. this._events.splice(index, 1);
  40142. index--;
  40143. }
  40144. }
  40145. };
  40146. Animation.prototype.getEvents = function () {
  40147. return this._events;
  40148. };
  40149. Animation.prototype.createRange = function (name, from, to) {
  40150. // check name not already in use; could happen for bones after serialized
  40151. if (!this._ranges[name]) {
  40152. this._ranges[name] = new AnimationRange(name, from, to);
  40153. }
  40154. };
  40155. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40156. if (deleteFrames === void 0) { deleteFrames = true; }
  40157. var range = this._ranges[name];
  40158. if (!range) {
  40159. return;
  40160. }
  40161. if (deleteFrames) {
  40162. var from = range.from;
  40163. var to = range.to;
  40164. // this loop MUST go high to low for multiple splices to work
  40165. for (var key = this._keys.length - 1; key >= 0; key--) {
  40166. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40167. this._keys.splice(key, 1);
  40168. }
  40169. }
  40170. }
  40171. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40172. };
  40173. Animation.prototype.getRange = function (name) {
  40174. return this._ranges[name];
  40175. };
  40176. Animation.prototype.getKeys = function () {
  40177. return this._keys;
  40178. };
  40179. Animation.prototype.getHighestFrame = function () {
  40180. var ret = 0;
  40181. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40182. if (ret < this._keys[key].frame) {
  40183. ret = this._keys[key].frame;
  40184. }
  40185. }
  40186. return ret;
  40187. };
  40188. Animation.prototype.getEasingFunction = function () {
  40189. return this._easingFunction;
  40190. };
  40191. Animation.prototype.setEasingFunction = function (easingFunction) {
  40192. this._easingFunction = easingFunction;
  40193. };
  40194. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40195. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40196. };
  40197. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40198. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40199. };
  40200. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40201. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40202. };
  40203. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40204. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40205. };
  40206. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40207. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40208. };
  40209. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40210. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40211. };
  40212. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40213. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40214. };
  40215. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40216. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40217. };
  40218. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40219. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40220. };
  40221. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40222. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40223. };
  40224. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40225. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40226. };
  40227. Animation.prototype.clone = function () {
  40228. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40229. clone.enableBlending = this.enableBlending;
  40230. clone.blendingSpeed = this.blendingSpeed;
  40231. if (this._keys) {
  40232. clone.setKeys(this._keys);
  40233. }
  40234. if (this._ranges) {
  40235. clone._ranges = {};
  40236. for (var name in this._ranges) {
  40237. var range = this._ranges[name];
  40238. if (!range) {
  40239. continue;
  40240. }
  40241. clone._ranges[name] = range.clone();
  40242. }
  40243. }
  40244. return clone;
  40245. };
  40246. Animation.prototype.setKeys = function (values) {
  40247. this._keys = values.slice(0);
  40248. };
  40249. Animation.prototype.serialize = function () {
  40250. var serializationObject = {};
  40251. serializationObject.name = this.name;
  40252. serializationObject.property = this.targetProperty;
  40253. serializationObject.framePerSecond = this.framePerSecond;
  40254. serializationObject.dataType = this.dataType;
  40255. serializationObject.loopBehavior = this.loopMode;
  40256. serializationObject.enableBlending = this.enableBlending;
  40257. serializationObject.blendingSpeed = this.blendingSpeed;
  40258. var dataType = this.dataType;
  40259. serializationObject.keys = [];
  40260. var keys = this.getKeys();
  40261. for (var index = 0; index < keys.length; index++) {
  40262. var animationKey = keys[index];
  40263. var key = {};
  40264. key.frame = animationKey.frame;
  40265. switch (dataType) {
  40266. case Animation.ANIMATIONTYPE_FLOAT:
  40267. key.values = [animationKey.value];
  40268. break;
  40269. case Animation.ANIMATIONTYPE_QUATERNION:
  40270. case Animation.ANIMATIONTYPE_MATRIX:
  40271. case Animation.ANIMATIONTYPE_VECTOR3:
  40272. case Animation.ANIMATIONTYPE_COLOR3:
  40273. key.values = animationKey.value.asArray();
  40274. break;
  40275. }
  40276. serializationObject.keys.push(key);
  40277. }
  40278. serializationObject.ranges = [];
  40279. for (var name in this._ranges) {
  40280. var source = this._ranges[name];
  40281. if (!source) {
  40282. continue;
  40283. }
  40284. var range = {};
  40285. range.name = name;
  40286. range.from = source.from;
  40287. range.to = source.to;
  40288. serializationObject.ranges.push(range);
  40289. }
  40290. return serializationObject;
  40291. };
  40292. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40293. get: function () {
  40294. return Animation._ANIMATIONTYPE_FLOAT;
  40295. },
  40296. enumerable: true,
  40297. configurable: true
  40298. });
  40299. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40300. get: function () {
  40301. return Animation._ANIMATIONTYPE_VECTOR3;
  40302. },
  40303. enumerable: true,
  40304. configurable: true
  40305. });
  40306. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40307. get: function () {
  40308. return Animation._ANIMATIONTYPE_VECTOR2;
  40309. },
  40310. enumerable: true,
  40311. configurable: true
  40312. });
  40313. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40314. get: function () {
  40315. return Animation._ANIMATIONTYPE_SIZE;
  40316. },
  40317. enumerable: true,
  40318. configurable: true
  40319. });
  40320. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  40321. get: function () {
  40322. return Animation._ANIMATIONTYPE_QUATERNION;
  40323. },
  40324. enumerable: true,
  40325. configurable: true
  40326. });
  40327. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40328. get: function () {
  40329. return Animation._ANIMATIONTYPE_MATRIX;
  40330. },
  40331. enumerable: true,
  40332. configurable: true
  40333. });
  40334. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40335. get: function () {
  40336. return Animation._ANIMATIONTYPE_COLOR3;
  40337. },
  40338. enumerable: true,
  40339. configurable: true
  40340. });
  40341. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40342. get: function () {
  40343. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40344. },
  40345. enumerable: true,
  40346. configurable: true
  40347. });
  40348. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40349. get: function () {
  40350. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40351. },
  40352. enumerable: true,
  40353. configurable: true
  40354. });
  40355. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40356. get: function () {
  40357. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40358. },
  40359. enumerable: true,
  40360. configurable: true
  40361. });
  40362. Animation.Parse = function (parsedAnimation) {
  40363. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40364. var dataType = parsedAnimation.dataType;
  40365. var keys = [];
  40366. var data;
  40367. var index;
  40368. if (parsedAnimation.enableBlending) {
  40369. animation.enableBlending = parsedAnimation.enableBlending;
  40370. }
  40371. if (parsedAnimation.blendingSpeed) {
  40372. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40373. }
  40374. for (index = 0; index < parsedAnimation.keys.length; index++) {
  40375. var key = parsedAnimation.keys[index];
  40376. var inTangent;
  40377. var outTangent;
  40378. switch (dataType) {
  40379. case Animation.ANIMATIONTYPE_FLOAT:
  40380. data = key.values[0];
  40381. if (key.values.length >= 1) {
  40382. inTangent = key.values[1];
  40383. }
  40384. if (key.values.length >= 2) {
  40385. outTangent = key.values[2];
  40386. }
  40387. break;
  40388. case Animation.ANIMATIONTYPE_QUATERNION:
  40389. data = BABYLON.Quaternion.FromArray(key.values);
  40390. if (key.values.length >= 8) {
  40391. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  40392. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  40393. inTangent = _inTangent;
  40394. }
  40395. }
  40396. if (key.values.length >= 12) {
  40397. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  40398. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  40399. outTangent = _outTangent;
  40400. }
  40401. }
  40402. break;
  40403. case Animation.ANIMATIONTYPE_MATRIX:
  40404. data = BABYLON.Matrix.FromArray(key.values);
  40405. break;
  40406. case Animation.ANIMATIONTYPE_COLOR3:
  40407. data = BABYLON.Color3.FromArray(key.values);
  40408. break;
  40409. case Animation.ANIMATIONTYPE_VECTOR3:
  40410. default:
  40411. data = BABYLON.Vector3.FromArray(key.values);
  40412. break;
  40413. }
  40414. var keyData = {};
  40415. keyData.frame = key.frame;
  40416. keyData.value = data;
  40417. if (inTangent != undefined) {
  40418. keyData.inTangent = inTangent;
  40419. }
  40420. if (outTangent != undefined) {
  40421. keyData.outTangent = outTangent;
  40422. }
  40423. keys.push(keyData);
  40424. }
  40425. animation.setKeys(keys);
  40426. if (parsedAnimation.ranges) {
  40427. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  40428. data = parsedAnimation.ranges[index];
  40429. animation.createRange(data.name, data.from, data.to);
  40430. }
  40431. }
  40432. return animation;
  40433. };
  40434. Animation.AppendSerializedAnimations = function (source, destination) {
  40435. if (source.animations) {
  40436. destination.animations = [];
  40437. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  40438. var animation = source.animations[animationIndex];
  40439. destination.animations.push(animation.serialize());
  40440. }
  40441. }
  40442. };
  40443. Animation.AllowMatricesInterpolation = false;
  40444. // Statics
  40445. Animation._ANIMATIONTYPE_FLOAT = 0;
  40446. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  40447. Animation._ANIMATIONTYPE_QUATERNION = 2;
  40448. Animation._ANIMATIONTYPE_MATRIX = 3;
  40449. Animation._ANIMATIONTYPE_COLOR3 = 4;
  40450. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  40451. Animation._ANIMATIONTYPE_SIZE = 6;
  40452. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  40453. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  40454. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  40455. return Animation;
  40456. }());
  40457. BABYLON.Animation = Animation;
  40458. })(BABYLON || (BABYLON = {}));
  40459. //# sourceMappingURL=babylon.animation.js.map
  40460. var BABYLON;
  40461. (function (BABYLON) {
  40462. var RuntimeAnimation = /** @class */ (function () {
  40463. function RuntimeAnimation(target, animation) {
  40464. this._offsetsCache = {};
  40465. this._highLimitsCache = {};
  40466. this._stopped = false;
  40467. this._blendingFactor = 0;
  40468. this._ratioOffset = 0;
  40469. this._animation = animation;
  40470. this._target = target;
  40471. animation._runtimeAnimations.push(this);
  40472. }
  40473. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  40474. get: function () {
  40475. return this._animation;
  40476. },
  40477. enumerable: true,
  40478. configurable: true
  40479. });
  40480. RuntimeAnimation.prototype.reset = function () {
  40481. this._offsetsCache = {};
  40482. this._highLimitsCache = {};
  40483. this.currentFrame = 0;
  40484. this._blendingFactor = 0;
  40485. this._originalBlendValue = null;
  40486. };
  40487. RuntimeAnimation.prototype.isStopped = function () {
  40488. return this._stopped;
  40489. };
  40490. RuntimeAnimation.prototype.dispose = function () {
  40491. var index = this._animation.runtimeAnimations.indexOf(this);
  40492. if (index > -1) {
  40493. this._animation.runtimeAnimations.splice(index, 1);
  40494. }
  40495. };
  40496. RuntimeAnimation.prototype._getKeyValue = function (value) {
  40497. if (typeof value === "function") {
  40498. return value();
  40499. }
  40500. return value;
  40501. };
  40502. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  40503. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  40504. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  40505. }
  40506. this.currentFrame = currentFrame;
  40507. var keys = this._animation.getKeys();
  40508. // Try to get a hash to find the right key
  40509. 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));
  40510. if (keys[startKeyIndex].frame >= currentFrame) {
  40511. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  40512. startKeyIndex--;
  40513. }
  40514. }
  40515. for (var key = startKeyIndex; key < keys.length; key++) {
  40516. var endKey = keys[key + 1];
  40517. if (endKey.frame >= currentFrame) {
  40518. var startKey = keys[key];
  40519. var startValue = this._getKeyValue(startKey.value);
  40520. var endValue = this._getKeyValue(endKey.value);
  40521. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  40522. var frameDelta = endKey.frame - startKey.frame;
  40523. // gradient : percent of currentFrame between the frame inf and the frame sup
  40524. var gradient = (currentFrame - startKey.frame) / frameDelta;
  40525. // check for easingFunction and correction of gradient
  40526. var easingFunction = this._animation.getEasingFunction();
  40527. if (easingFunction != null) {
  40528. gradient = easingFunction.ease(gradient);
  40529. }
  40530. switch (this._animation.dataType) {
  40531. // Float
  40532. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40533. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  40534. switch (loopMode) {
  40535. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40536. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40537. return floatValue;
  40538. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40539. return offsetValue * repeatCount + floatValue;
  40540. }
  40541. break;
  40542. // Quaternion
  40543. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40544. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  40545. switch (loopMode) {
  40546. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40547. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40548. return quatValue;
  40549. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40550. return quatValue.add(offsetValue.scale(repeatCount));
  40551. }
  40552. return quatValue;
  40553. // Vector3
  40554. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40555. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  40556. switch (loopMode) {
  40557. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40558. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40559. return vec3Value;
  40560. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40561. return vec3Value.add(offsetValue.scale(repeatCount));
  40562. }
  40563. // Vector2
  40564. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40565. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  40566. switch (loopMode) {
  40567. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40568. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40569. return vec2Value;
  40570. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40571. return vec2Value.add(offsetValue.scale(repeatCount));
  40572. }
  40573. // Size
  40574. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40575. switch (loopMode) {
  40576. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40577. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40578. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  40579. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40580. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40581. }
  40582. // Color3
  40583. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40584. switch (loopMode) {
  40585. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40586. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40587. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  40588. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40589. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40590. }
  40591. // Matrix
  40592. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  40593. switch (loopMode) {
  40594. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40595. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40596. if (BABYLON.Animation.AllowMatricesInterpolation) {
  40597. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  40598. }
  40599. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40600. return startValue;
  40601. }
  40602. default:
  40603. break;
  40604. }
  40605. break;
  40606. }
  40607. }
  40608. return this._getKeyValue(keys[keys.length - 1].value);
  40609. };
  40610. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  40611. if (blend === void 0) { blend = false; }
  40612. // Set value
  40613. var path;
  40614. var destination;
  40615. var targetPropertyPath = this._animation.targetPropertyPath;
  40616. if (targetPropertyPath.length > 1) {
  40617. var property = this._target[targetPropertyPath[0]];
  40618. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  40619. property = property[targetPropertyPath[index]];
  40620. }
  40621. path = targetPropertyPath[targetPropertyPath.length - 1];
  40622. destination = property;
  40623. }
  40624. else {
  40625. path = targetPropertyPath[0];
  40626. destination = this._target;
  40627. }
  40628. // Blending
  40629. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  40630. if (!this._originalBlendValue) {
  40631. if (destination[path].clone) {
  40632. this._originalBlendValue = destination[path].clone();
  40633. }
  40634. else {
  40635. this._originalBlendValue = destination[path];
  40636. }
  40637. }
  40638. if (this._originalBlendValue.prototype) {
  40639. if (this._originalBlendValue.prototype.Lerp) {
  40640. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  40641. }
  40642. else {
  40643. destination[path] = currentValue;
  40644. }
  40645. }
  40646. else if (this._originalBlendValue.m) {
  40647. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  40648. }
  40649. else {
  40650. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  40651. }
  40652. this._blendingFactor += this._animation.blendingSpeed;
  40653. }
  40654. else {
  40655. destination[path] = currentValue;
  40656. }
  40657. if (this._target.markAsDirty) {
  40658. this._target.markAsDirty(this._animation.targetProperty);
  40659. }
  40660. };
  40661. RuntimeAnimation.prototype.goToFrame = function (frame) {
  40662. var keys = this._animation.getKeys();
  40663. if (frame < keys[0].frame) {
  40664. frame = keys[0].frame;
  40665. }
  40666. else if (frame > keys[keys.length - 1].frame) {
  40667. frame = keys[keys.length - 1].frame;
  40668. }
  40669. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  40670. this.setValue(currentValue);
  40671. };
  40672. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  40673. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  40674. this._ratioOffset = this._previousRatio - newRatio;
  40675. };
  40676. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  40677. if (blend === void 0) { blend = false; }
  40678. var targetPropertyPath = this._animation.targetPropertyPath;
  40679. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  40680. this._stopped = true;
  40681. return false;
  40682. }
  40683. var returnValue = true;
  40684. var keys = this._animation.getKeys();
  40685. // Adding a start key at frame 0 if missing
  40686. if (keys[0].frame !== 0) {
  40687. var newKey = { frame: 0, value: keys[0].value };
  40688. keys.splice(0, 0, newKey);
  40689. }
  40690. // Check limits
  40691. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  40692. from = keys[0].frame;
  40693. }
  40694. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  40695. to = keys[keys.length - 1].frame;
  40696. }
  40697. //to and from cannot be the same key
  40698. if (from === to) {
  40699. if (from > keys[0].frame) {
  40700. from--;
  40701. }
  40702. else if (to < keys[keys.length - 1].frame) {
  40703. to++;
  40704. }
  40705. }
  40706. // Compute ratio
  40707. var range = to - from;
  40708. var offsetValue;
  40709. // ratio represents the frame delta between from and to
  40710. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  40711. var highLimitValue = 0;
  40712. this._previousDelay = delay;
  40713. this._previousRatio = ratio;
  40714. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  40715. returnValue = false;
  40716. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  40717. }
  40718. else {
  40719. // Get max value if required
  40720. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  40721. var keyOffset = to.toString() + from.toString();
  40722. if (!this._offsetsCache[keyOffset]) {
  40723. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40724. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40725. switch (this._animation.dataType) {
  40726. // Float
  40727. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40728. this._offsetsCache[keyOffset] = toValue - fromValue;
  40729. break;
  40730. // Quaternion
  40731. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40732. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40733. break;
  40734. // Vector3
  40735. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40736. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40737. // Vector2
  40738. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40739. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40740. // Size
  40741. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40742. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40743. // Color3
  40744. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40745. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40746. default:
  40747. break;
  40748. }
  40749. this._highLimitsCache[keyOffset] = toValue;
  40750. }
  40751. highLimitValue = this._highLimitsCache[keyOffset];
  40752. offsetValue = this._offsetsCache[keyOffset];
  40753. }
  40754. }
  40755. if (offsetValue === undefined) {
  40756. switch (this._animation.dataType) {
  40757. // Float
  40758. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40759. offsetValue = 0;
  40760. break;
  40761. // Quaternion
  40762. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40763. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  40764. break;
  40765. // Vector3
  40766. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40767. offsetValue = BABYLON.Vector3.Zero();
  40768. break;
  40769. // Vector2
  40770. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40771. offsetValue = BABYLON.Vector2.Zero();
  40772. break;
  40773. // Size
  40774. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40775. offsetValue = BABYLON.Size.Zero();
  40776. break;
  40777. // Color3
  40778. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40779. offsetValue = BABYLON.Color3.Black();
  40780. }
  40781. }
  40782. // Compute value
  40783. var repeatCount = (ratio / range) >> 0;
  40784. var currentFrame = returnValue ? from + ratio % range : to;
  40785. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  40786. // Set value
  40787. this.setValue(currentValue);
  40788. // Check events
  40789. var events = this._animation.getEvents();
  40790. for (var index = 0; index < events.length; index++) {
  40791. // Make sure current frame has passed event frame and that event frame is within the current range
  40792. // Also, handle both forward and reverse animations
  40793. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  40794. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  40795. var event = events[index];
  40796. if (!event.isDone) {
  40797. // If event should be done only once, remove it.
  40798. if (event.onlyOnce) {
  40799. events.splice(index, 1);
  40800. index--;
  40801. }
  40802. event.isDone = true;
  40803. event.action();
  40804. } // Don't do anything if the event has already be done.
  40805. }
  40806. else if (events[index].isDone && !events[index].onlyOnce) {
  40807. // reset event, the animation is looping
  40808. events[index].isDone = false;
  40809. }
  40810. }
  40811. if (!returnValue) {
  40812. this._stopped = true;
  40813. }
  40814. return returnValue;
  40815. };
  40816. return RuntimeAnimation;
  40817. }());
  40818. BABYLON.RuntimeAnimation = RuntimeAnimation;
  40819. })(BABYLON || (BABYLON = {}));
  40820. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  40821. var BABYLON;
  40822. (function (BABYLON) {
  40823. var Animatable = /** @class */ (function () {
  40824. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  40825. if (fromFrame === void 0) { fromFrame = 0; }
  40826. if (toFrame === void 0) { toFrame = 100; }
  40827. if (loopAnimation === void 0) { loopAnimation = false; }
  40828. if (speedRatio === void 0) { speedRatio = 1.0; }
  40829. this.target = target;
  40830. this.fromFrame = fromFrame;
  40831. this.toFrame = toFrame;
  40832. this.loopAnimation = loopAnimation;
  40833. this.onAnimationEnd = onAnimationEnd;
  40834. this._localDelayOffset = null;
  40835. this._pausedDelay = null;
  40836. this._runtimeAnimations = new Array();
  40837. this._paused = false;
  40838. this._speedRatio = 1;
  40839. this.animationStarted = false;
  40840. if (animations) {
  40841. this.appendAnimations(target, animations);
  40842. }
  40843. this._speedRatio = speedRatio;
  40844. this._scene = scene;
  40845. scene._activeAnimatables.push(this);
  40846. }
  40847. Object.defineProperty(Animatable.prototype, "speedRatio", {
  40848. get: function () {
  40849. return this._speedRatio;
  40850. },
  40851. set: function (value) {
  40852. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  40853. var animation = this._runtimeAnimations[index];
  40854. animation._prepareForSpeedRatioChange(value);
  40855. }
  40856. this._speedRatio = value;
  40857. },
  40858. enumerable: true,
  40859. configurable: true
  40860. });
  40861. // Methods
  40862. Animatable.prototype.getAnimations = function () {
  40863. return this._runtimeAnimations;
  40864. };
  40865. Animatable.prototype.appendAnimations = function (target, animations) {
  40866. for (var index = 0; index < animations.length; index++) {
  40867. var animation = animations[index];
  40868. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  40869. }
  40870. };
  40871. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  40872. var runtimeAnimations = this._runtimeAnimations;
  40873. for (var index = 0; index < runtimeAnimations.length; index++) {
  40874. if (runtimeAnimations[index].animation.targetProperty === property) {
  40875. return runtimeAnimations[index].animation;
  40876. }
  40877. }
  40878. return null;
  40879. };
  40880. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  40881. var runtimeAnimations = this._runtimeAnimations;
  40882. for (var index = 0; index < runtimeAnimations.length; index++) {
  40883. if (runtimeAnimations[index].animation.targetProperty === property) {
  40884. return runtimeAnimations[index];
  40885. }
  40886. }
  40887. return null;
  40888. };
  40889. Animatable.prototype.reset = function () {
  40890. var runtimeAnimations = this._runtimeAnimations;
  40891. for (var index = 0; index < runtimeAnimations.length; index++) {
  40892. runtimeAnimations[index].reset();
  40893. }
  40894. this._localDelayOffset = null;
  40895. this._pausedDelay = null;
  40896. };
  40897. Animatable.prototype.enableBlending = function (blendingSpeed) {
  40898. var runtimeAnimations = this._runtimeAnimations;
  40899. for (var index = 0; index < runtimeAnimations.length; index++) {
  40900. runtimeAnimations[index].animation.enableBlending = true;
  40901. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  40902. }
  40903. };
  40904. Animatable.prototype.disableBlending = function () {
  40905. var runtimeAnimations = this._runtimeAnimations;
  40906. for (var index = 0; index < runtimeAnimations.length; index++) {
  40907. runtimeAnimations[index].animation.enableBlending = false;
  40908. }
  40909. };
  40910. Animatable.prototype.goToFrame = function (frame) {
  40911. var runtimeAnimations = this._runtimeAnimations;
  40912. if (runtimeAnimations[0]) {
  40913. var fps = runtimeAnimations[0].animation.framePerSecond;
  40914. var currentFrame = runtimeAnimations[0].currentFrame;
  40915. var adjustTime = frame - currentFrame;
  40916. var delay = adjustTime * 1000 / fps;
  40917. if (this._localDelayOffset === null) {
  40918. this._localDelayOffset = 0;
  40919. }
  40920. this._localDelayOffset -= delay;
  40921. }
  40922. for (var index = 0; index < runtimeAnimations.length; index++) {
  40923. runtimeAnimations[index].goToFrame(frame);
  40924. }
  40925. };
  40926. Animatable.prototype.pause = function () {
  40927. if (this._paused) {
  40928. return;
  40929. }
  40930. this._paused = true;
  40931. };
  40932. Animatable.prototype.restart = function () {
  40933. this._paused = false;
  40934. };
  40935. Animatable.prototype.stop = function (animationName) {
  40936. if (animationName) {
  40937. var idx = this._scene._activeAnimatables.indexOf(this);
  40938. if (idx > -1) {
  40939. var runtimeAnimations = this._runtimeAnimations;
  40940. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  40941. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  40942. continue;
  40943. }
  40944. runtimeAnimations[index].dispose();
  40945. runtimeAnimations.splice(index, 1);
  40946. }
  40947. if (runtimeAnimations.length == 0) {
  40948. this._scene._activeAnimatables.splice(idx, 1);
  40949. if (this.onAnimationEnd) {
  40950. this.onAnimationEnd();
  40951. }
  40952. }
  40953. }
  40954. }
  40955. else {
  40956. var index = this._scene._activeAnimatables.indexOf(this);
  40957. if (index > -1) {
  40958. this._scene._activeAnimatables.splice(index, 1);
  40959. var runtimeAnimations = this._runtimeAnimations;
  40960. for (var index = 0; index < runtimeAnimations.length; index++) {
  40961. runtimeAnimations[index].dispose();
  40962. }
  40963. if (this.onAnimationEnd) {
  40964. this.onAnimationEnd();
  40965. }
  40966. }
  40967. }
  40968. };
  40969. Animatable.prototype._animate = function (delay) {
  40970. if (this._paused) {
  40971. this.animationStarted = false;
  40972. if (this._pausedDelay === null) {
  40973. this._pausedDelay = delay;
  40974. }
  40975. return true;
  40976. }
  40977. if (this._localDelayOffset === null) {
  40978. this._localDelayOffset = delay;
  40979. }
  40980. else if (this._pausedDelay !== null) {
  40981. this._localDelayOffset += delay - this._pausedDelay;
  40982. this._pausedDelay = null;
  40983. }
  40984. // Animating
  40985. var running = false;
  40986. var runtimeAnimations = this._runtimeAnimations;
  40987. var index;
  40988. for (index = 0; index < runtimeAnimations.length; index++) {
  40989. var animation = runtimeAnimations[index];
  40990. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  40991. running = running || isRunning;
  40992. }
  40993. this.animationStarted = running;
  40994. if (!running) {
  40995. // Remove from active animatables
  40996. index = this._scene._activeAnimatables.indexOf(this);
  40997. this._scene._activeAnimatables.splice(index, 1);
  40998. // Dispose all runtime animations
  40999. for (index = 0; index < runtimeAnimations.length; index++) {
  41000. runtimeAnimations[index].dispose();
  41001. }
  41002. }
  41003. if (!running && this.onAnimationEnd) {
  41004. this.onAnimationEnd();
  41005. this.onAnimationEnd = null;
  41006. }
  41007. return running;
  41008. };
  41009. return Animatable;
  41010. }());
  41011. BABYLON.Animatable = Animatable;
  41012. })(BABYLON || (BABYLON = {}));
  41013. //# sourceMappingURL=babylon.animatable.js.map
  41014. var BABYLON;
  41015. (function (BABYLON) {
  41016. var EasingFunction = /** @class */ (function () {
  41017. function EasingFunction() {
  41018. // Properties
  41019. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  41020. }
  41021. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  41022. get: function () {
  41023. return EasingFunction._EASINGMODE_EASEIN;
  41024. },
  41025. enumerable: true,
  41026. configurable: true
  41027. });
  41028. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  41029. get: function () {
  41030. return EasingFunction._EASINGMODE_EASEOUT;
  41031. },
  41032. enumerable: true,
  41033. configurable: true
  41034. });
  41035. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  41036. get: function () {
  41037. return EasingFunction._EASINGMODE_EASEINOUT;
  41038. },
  41039. enumerable: true,
  41040. configurable: true
  41041. });
  41042. EasingFunction.prototype.setEasingMode = function (easingMode) {
  41043. var n = Math.min(Math.max(easingMode, 0), 2);
  41044. this._easingMode = n;
  41045. };
  41046. EasingFunction.prototype.getEasingMode = function () {
  41047. return this._easingMode;
  41048. };
  41049. EasingFunction.prototype.easeInCore = function (gradient) {
  41050. throw new Error('You must implement this method');
  41051. };
  41052. EasingFunction.prototype.ease = function (gradient) {
  41053. switch (this._easingMode) {
  41054. case EasingFunction.EASINGMODE_EASEIN:
  41055. return this.easeInCore(gradient);
  41056. case EasingFunction.EASINGMODE_EASEOUT:
  41057. return (1 - this.easeInCore(1 - gradient));
  41058. }
  41059. if (gradient >= 0.5) {
  41060. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  41061. }
  41062. return (this.easeInCore(gradient * 2) * 0.5);
  41063. };
  41064. //Statics
  41065. EasingFunction._EASINGMODE_EASEIN = 0;
  41066. EasingFunction._EASINGMODE_EASEOUT = 1;
  41067. EasingFunction._EASINGMODE_EASEINOUT = 2;
  41068. return EasingFunction;
  41069. }());
  41070. BABYLON.EasingFunction = EasingFunction;
  41071. var CircleEase = /** @class */ (function (_super) {
  41072. __extends(CircleEase, _super);
  41073. function CircleEase() {
  41074. return _super !== null && _super.apply(this, arguments) || this;
  41075. }
  41076. CircleEase.prototype.easeInCore = function (gradient) {
  41077. gradient = Math.max(0, Math.min(1, gradient));
  41078. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  41079. };
  41080. return CircleEase;
  41081. }(EasingFunction));
  41082. BABYLON.CircleEase = CircleEase;
  41083. var BackEase = /** @class */ (function (_super) {
  41084. __extends(BackEase, _super);
  41085. function BackEase(amplitude) {
  41086. if (amplitude === void 0) { amplitude = 1; }
  41087. var _this = _super.call(this) || this;
  41088. _this.amplitude = amplitude;
  41089. return _this;
  41090. }
  41091. BackEase.prototype.easeInCore = function (gradient) {
  41092. var num = Math.max(0, this.amplitude);
  41093. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41094. };
  41095. return BackEase;
  41096. }(EasingFunction));
  41097. BABYLON.BackEase = BackEase;
  41098. var BounceEase = /** @class */ (function (_super) {
  41099. __extends(BounceEase, _super);
  41100. function BounceEase(bounces, bounciness) {
  41101. if (bounces === void 0) { bounces = 3; }
  41102. if (bounciness === void 0) { bounciness = 2; }
  41103. var _this = _super.call(this) || this;
  41104. _this.bounces = bounces;
  41105. _this.bounciness = bounciness;
  41106. return _this;
  41107. }
  41108. BounceEase.prototype.easeInCore = function (gradient) {
  41109. var y = Math.max(0.0, this.bounces);
  41110. var bounciness = this.bounciness;
  41111. if (bounciness <= 1.0) {
  41112. bounciness = 1.001;
  41113. }
  41114. var num9 = Math.pow(bounciness, y);
  41115. var num5 = 1.0 - bounciness;
  41116. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41117. var num15 = gradient * num4;
  41118. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41119. var num3 = Math.floor(num65);
  41120. var num13 = num3 + 1.0;
  41121. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41122. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41123. var num7 = (num8 + num12) * 0.5;
  41124. var num6 = gradient - num7;
  41125. var num2 = num7 - num8;
  41126. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41127. };
  41128. return BounceEase;
  41129. }(EasingFunction));
  41130. BABYLON.BounceEase = BounceEase;
  41131. var CubicEase = /** @class */ (function (_super) {
  41132. __extends(CubicEase, _super);
  41133. function CubicEase() {
  41134. return _super !== null && _super.apply(this, arguments) || this;
  41135. }
  41136. CubicEase.prototype.easeInCore = function (gradient) {
  41137. return (gradient * gradient * gradient);
  41138. };
  41139. return CubicEase;
  41140. }(EasingFunction));
  41141. BABYLON.CubicEase = CubicEase;
  41142. var ElasticEase = /** @class */ (function (_super) {
  41143. __extends(ElasticEase, _super);
  41144. function ElasticEase(oscillations, springiness) {
  41145. if (oscillations === void 0) { oscillations = 3; }
  41146. if (springiness === void 0) { springiness = 3; }
  41147. var _this = _super.call(this) || this;
  41148. _this.oscillations = oscillations;
  41149. _this.springiness = springiness;
  41150. return _this;
  41151. }
  41152. ElasticEase.prototype.easeInCore = function (gradient) {
  41153. var num2;
  41154. var num3 = Math.max(0.0, this.oscillations);
  41155. var num = Math.max(0.0, this.springiness);
  41156. if (num == 0) {
  41157. num2 = gradient;
  41158. }
  41159. else {
  41160. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41161. }
  41162. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41163. };
  41164. return ElasticEase;
  41165. }(EasingFunction));
  41166. BABYLON.ElasticEase = ElasticEase;
  41167. var ExponentialEase = /** @class */ (function (_super) {
  41168. __extends(ExponentialEase, _super);
  41169. function ExponentialEase(exponent) {
  41170. if (exponent === void 0) { exponent = 2; }
  41171. var _this = _super.call(this) || this;
  41172. _this.exponent = exponent;
  41173. return _this;
  41174. }
  41175. ExponentialEase.prototype.easeInCore = function (gradient) {
  41176. if (this.exponent <= 0) {
  41177. return gradient;
  41178. }
  41179. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41180. };
  41181. return ExponentialEase;
  41182. }(EasingFunction));
  41183. BABYLON.ExponentialEase = ExponentialEase;
  41184. var PowerEase = /** @class */ (function (_super) {
  41185. __extends(PowerEase, _super);
  41186. function PowerEase(power) {
  41187. if (power === void 0) { power = 2; }
  41188. var _this = _super.call(this) || this;
  41189. _this.power = power;
  41190. return _this;
  41191. }
  41192. PowerEase.prototype.easeInCore = function (gradient) {
  41193. var y = Math.max(0.0, this.power);
  41194. return Math.pow(gradient, y);
  41195. };
  41196. return PowerEase;
  41197. }(EasingFunction));
  41198. BABYLON.PowerEase = PowerEase;
  41199. var QuadraticEase = /** @class */ (function (_super) {
  41200. __extends(QuadraticEase, _super);
  41201. function QuadraticEase() {
  41202. return _super !== null && _super.apply(this, arguments) || this;
  41203. }
  41204. QuadraticEase.prototype.easeInCore = function (gradient) {
  41205. return (gradient * gradient);
  41206. };
  41207. return QuadraticEase;
  41208. }(EasingFunction));
  41209. BABYLON.QuadraticEase = QuadraticEase;
  41210. var QuarticEase = /** @class */ (function (_super) {
  41211. __extends(QuarticEase, _super);
  41212. function QuarticEase() {
  41213. return _super !== null && _super.apply(this, arguments) || this;
  41214. }
  41215. QuarticEase.prototype.easeInCore = function (gradient) {
  41216. return (gradient * gradient * gradient * gradient);
  41217. };
  41218. return QuarticEase;
  41219. }(EasingFunction));
  41220. BABYLON.QuarticEase = QuarticEase;
  41221. var QuinticEase = /** @class */ (function (_super) {
  41222. __extends(QuinticEase, _super);
  41223. function QuinticEase() {
  41224. return _super !== null && _super.apply(this, arguments) || this;
  41225. }
  41226. QuinticEase.prototype.easeInCore = function (gradient) {
  41227. return (gradient * gradient * gradient * gradient * gradient);
  41228. };
  41229. return QuinticEase;
  41230. }(EasingFunction));
  41231. BABYLON.QuinticEase = QuinticEase;
  41232. var SineEase = /** @class */ (function (_super) {
  41233. __extends(SineEase, _super);
  41234. function SineEase() {
  41235. return _super !== null && _super.apply(this, arguments) || this;
  41236. }
  41237. SineEase.prototype.easeInCore = function (gradient) {
  41238. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41239. };
  41240. return SineEase;
  41241. }(EasingFunction));
  41242. BABYLON.SineEase = SineEase;
  41243. var BezierCurveEase = /** @class */ (function (_super) {
  41244. __extends(BezierCurveEase, _super);
  41245. function BezierCurveEase(x1, y1, x2, y2) {
  41246. if (x1 === void 0) { x1 = 0; }
  41247. if (y1 === void 0) { y1 = 0; }
  41248. if (x2 === void 0) { x2 = 1; }
  41249. if (y2 === void 0) { y2 = 1; }
  41250. var _this = _super.call(this) || this;
  41251. _this.x1 = x1;
  41252. _this.y1 = y1;
  41253. _this.x2 = x2;
  41254. _this.y2 = y2;
  41255. return _this;
  41256. }
  41257. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41258. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41259. };
  41260. return BezierCurveEase;
  41261. }(EasingFunction));
  41262. BABYLON.BezierCurveEase = BezierCurveEase;
  41263. })(BABYLON || (BABYLON = {}));
  41264. //# sourceMappingURL=babylon.easing.js.map
  41265. var BABYLON;
  41266. (function (BABYLON) {
  41267. var Condition = /** @class */ (function () {
  41268. function Condition(actionManager) {
  41269. this._actionManager = actionManager;
  41270. }
  41271. Condition.prototype.isValid = function () {
  41272. return true;
  41273. };
  41274. Condition.prototype._getProperty = function (propertyPath) {
  41275. return this._actionManager._getProperty(propertyPath);
  41276. };
  41277. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41278. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41279. };
  41280. Condition.prototype.serialize = function () {
  41281. };
  41282. Condition.prototype._serialize = function (serializedCondition) {
  41283. return {
  41284. type: 2,
  41285. children: [],
  41286. name: serializedCondition.name,
  41287. properties: serializedCondition.properties
  41288. };
  41289. };
  41290. return Condition;
  41291. }());
  41292. BABYLON.Condition = Condition;
  41293. var ValueCondition = /** @class */ (function (_super) {
  41294. __extends(ValueCondition, _super);
  41295. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41296. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41297. var _this = _super.call(this, actionManager) || this;
  41298. _this.propertyPath = propertyPath;
  41299. _this.value = value;
  41300. _this.operator = operator;
  41301. _this._target = target;
  41302. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41303. _this._property = _this._getProperty(_this.propertyPath);
  41304. return _this;
  41305. }
  41306. Object.defineProperty(ValueCondition, "IsEqual", {
  41307. get: function () {
  41308. return ValueCondition._IsEqual;
  41309. },
  41310. enumerable: true,
  41311. configurable: true
  41312. });
  41313. Object.defineProperty(ValueCondition, "IsDifferent", {
  41314. get: function () {
  41315. return ValueCondition._IsDifferent;
  41316. },
  41317. enumerable: true,
  41318. configurable: true
  41319. });
  41320. Object.defineProperty(ValueCondition, "IsGreater", {
  41321. get: function () {
  41322. return ValueCondition._IsGreater;
  41323. },
  41324. enumerable: true,
  41325. configurable: true
  41326. });
  41327. Object.defineProperty(ValueCondition, "IsLesser", {
  41328. get: function () {
  41329. return ValueCondition._IsLesser;
  41330. },
  41331. enumerable: true,
  41332. configurable: true
  41333. });
  41334. // Methods
  41335. ValueCondition.prototype.isValid = function () {
  41336. switch (this.operator) {
  41337. case ValueCondition.IsGreater:
  41338. return this._effectiveTarget[this._property] > this.value;
  41339. case ValueCondition.IsLesser:
  41340. return this._effectiveTarget[this._property] < this.value;
  41341. case ValueCondition.IsEqual:
  41342. case ValueCondition.IsDifferent:
  41343. var check;
  41344. if (this.value.equals) {
  41345. check = this.value.equals(this._effectiveTarget[this._property]);
  41346. }
  41347. else {
  41348. check = this.value === this._effectiveTarget[this._property];
  41349. }
  41350. return this.operator === ValueCondition.IsEqual ? check : !check;
  41351. }
  41352. return false;
  41353. };
  41354. ValueCondition.prototype.serialize = function () {
  41355. return this._serialize({
  41356. name: "ValueCondition",
  41357. properties: [
  41358. BABYLON.Action._GetTargetProperty(this._target),
  41359. { name: "propertyPath", value: this.propertyPath },
  41360. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41361. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41362. ]
  41363. });
  41364. };
  41365. ValueCondition.GetOperatorName = function (operator) {
  41366. switch (operator) {
  41367. case ValueCondition._IsEqual: return "IsEqual";
  41368. case ValueCondition._IsDifferent: return "IsDifferent";
  41369. case ValueCondition._IsGreater: return "IsGreater";
  41370. case ValueCondition._IsLesser: return "IsLesser";
  41371. default: return "";
  41372. }
  41373. };
  41374. // Statics
  41375. ValueCondition._IsEqual = 0;
  41376. ValueCondition._IsDifferent = 1;
  41377. ValueCondition._IsGreater = 2;
  41378. ValueCondition._IsLesser = 3;
  41379. return ValueCondition;
  41380. }(Condition));
  41381. BABYLON.ValueCondition = ValueCondition;
  41382. var PredicateCondition = /** @class */ (function (_super) {
  41383. __extends(PredicateCondition, _super);
  41384. function PredicateCondition(actionManager, predicate) {
  41385. var _this = _super.call(this, actionManager) || this;
  41386. _this.predicate = predicate;
  41387. return _this;
  41388. }
  41389. PredicateCondition.prototype.isValid = function () {
  41390. return this.predicate();
  41391. };
  41392. return PredicateCondition;
  41393. }(Condition));
  41394. BABYLON.PredicateCondition = PredicateCondition;
  41395. var StateCondition = /** @class */ (function (_super) {
  41396. __extends(StateCondition, _super);
  41397. function StateCondition(actionManager, target, value) {
  41398. var _this = _super.call(this, actionManager) || this;
  41399. _this.value = value;
  41400. _this._target = target;
  41401. return _this;
  41402. }
  41403. // Methods
  41404. StateCondition.prototype.isValid = function () {
  41405. return this._target.state === this.value;
  41406. };
  41407. StateCondition.prototype.serialize = function () {
  41408. return this._serialize({
  41409. name: "StateCondition",
  41410. properties: [
  41411. BABYLON.Action._GetTargetProperty(this._target),
  41412. { name: "value", value: this.value }
  41413. ]
  41414. });
  41415. };
  41416. return StateCondition;
  41417. }(Condition));
  41418. BABYLON.StateCondition = StateCondition;
  41419. })(BABYLON || (BABYLON = {}));
  41420. //# sourceMappingURL=babylon.condition.js.map
  41421. var BABYLON;
  41422. (function (BABYLON) {
  41423. var Action = /** @class */ (function () {
  41424. function Action(triggerOptions, condition) {
  41425. this.triggerOptions = triggerOptions;
  41426. this.onBeforeExecuteObservable = new BABYLON.Observable();
  41427. if (triggerOptions.parameter) {
  41428. this.trigger = triggerOptions.trigger;
  41429. this._triggerParameter = triggerOptions.parameter;
  41430. }
  41431. else {
  41432. this.trigger = triggerOptions;
  41433. }
  41434. this._nextActiveAction = this;
  41435. this._condition = condition;
  41436. }
  41437. // Methods
  41438. Action.prototype._prepare = function () {
  41439. };
  41440. Action.prototype.getTriggerParameter = function () {
  41441. return this._triggerParameter;
  41442. };
  41443. Action.prototype._executeCurrent = function (evt) {
  41444. if (this._nextActiveAction._condition) {
  41445. var condition = this._nextActiveAction._condition;
  41446. var currentRenderId = this._actionManager.getScene().getRenderId();
  41447. // We cache the current evaluation for the current frame
  41448. if (condition._evaluationId === currentRenderId) {
  41449. if (!condition._currentResult) {
  41450. return;
  41451. }
  41452. }
  41453. else {
  41454. condition._evaluationId = currentRenderId;
  41455. if (!condition.isValid()) {
  41456. condition._currentResult = false;
  41457. return;
  41458. }
  41459. condition._currentResult = true;
  41460. }
  41461. }
  41462. this.onBeforeExecuteObservable.notifyObservers(this);
  41463. this._nextActiveAction.execute(evt);
  41464. this.skipToNextActiveAction();
  41465. };
  41466. Action.prototype.execute = function (evt) {
  41467. };
  41468. Action.prototype.skipToNextActiveAction = function () {
  41469. if (this._nextActiveAction._child) {
  41470. if (!this._nextActiveAction._child._actionManager) {
  41471. this._nextActiveAction._child._actionManager = this._actionManager;
  41472. }
  41473. this._nextActiveAction = this._nextActiveAction._child;
  41474. }
  41475. else {
  41476. this._nextActiveAction = this;
  41477. }
  41478. };
  41479. Action.prototype.then = function (action) {
  41480. this._child = action;
  41481. action._actionManager = this._actionManager;
  41482. action._prepare();
  41483. return action;
  41484. };
  41485. Action.prototype._getProperty = function (propertyPath) {
  41486. return this._actionManager._getProperty(propertyPath);
  41487. };
  41488. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41489. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41490. };
  41491. Action.prototype.serialize = function (parent) {
  41492. };
  41493. // Called by BABYLON.Action objects in serialize(...). Internal use
  41494. Action.prototype._serialize = function (serializedAction, parent) {
  41495. var serializationObject = {
  41496. type: 1,
  41497. children: [],
  41498. name: serializedAction.name,
  41499. properties: serializedAction.properties || []
  41500. };
  41501. // Serialize child
  41502. if (this._child) {
  41503. this._child.serialize(serializationObject);
  41504. }
  41505. // Check if "this" has a condition
  41506. if (this._condition) {
  41507. var serializedCondition = this._condition.serialize();
  41508. serializedCondition.children.push(serializationObject);
  41509. if (parent) {
  41510. parent.children.push(serializedCondition);
  41511. }
  41512. return serializedCondition;
  41513. }
  41514. if (parent) {
  41515. parent.children.push(serializationObject);
  41516. }
  41517. return serializationObject;
  41518. };
  41519. Action._SerializeValueAsString = function (value) {
  41520. if (typeof value === "number") {
  41521. return value.toString();
  41522. }
  41523. if (typeof value === "boolean") {
  41524. return value ? "true" : "false";
  41525. }
  41526. if (value instanceof BABYLON.Vector2) {
  41527. return value.x + ", " + value.y;
  41528. }
  41529. if (value instanceof BABYLON.Vector3) {
  41530. return value.x + ", " + value.y + ", " + value.z;
  41531. }
  41532. if (value instanceof BABYLON.Color3) {
  41533. return value.r + ", " + value.g + ", " + value.b;
  41534. }
  41535. if (value instanceof BABYLON.Color4) {
  41536. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41537. }
  41538. return value; // string
  41539. };
  41540. Action._GetTargetProperty = function (target) {
  41541. return {
  41542. name: "target",
  41543. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41544. : target instanceof BABYLON.Light ? "LightProperties"
  41545. : target instanceof BABYLON.Camera ? "CameraProperties"
  41546. : "SceneProperties",
  41547. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41548. };
  41549. };
  41550. return Action;
  41551. }());
  41552. BABYLON.Action = Action;
  41553. })(BABYLON || (BABYLON = {}));
  41554. //# sourceMappingURL=babylon.action.js.map
  41555. var BABYLON;
  41556. (function (BABYLON) {
  41557. /**
  41558. * ActionEvent is the event beint sent when an action is triggered.
  41559. */
  41560. var ActionEvent = /** @class */ (function () {
  41561. /**
  41562. * @param source The mesh or sprite that triggered the action.
  41563. * @param pointerX The X mouse cursor position at the time of the event
  41564. * @param pointerY The Y mouse cursor position at the time of the event
  41565. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41566. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41567. */
  41568. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41569. this.source = source;
  41570. this.pointerX = pointerX;
  41571. this.pointerY = pointerY;
  41572. this.meshUnderPointer = meshUnderPointer;
  41573. this.sourceEvent = sourceEvent;
  41574. this.additionalData = additionalData;
  41575. }
  41576. /**
  41577. * Helper function to auto-create an ActionEvent from a source mesh.
  41578. * @param source The source mesh that triggered the event
  41579. * @param evt {Event} The original (browser) event
  41580. */
  41581. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41582. var scene = source.getScene();
  41583. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41584. };
  41585. /**
  41586. * Helper function to auto-create an ActionEvent from a source mesh.
  41587. * @param source The source sprite that triggered the event
  41588. * @param scene Scene associated with the sprite
  41589. * @param evt {Event} The original (browser) event
  41590. */
  41591. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41592. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41593. };
  41594. /**
  41595. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41596. * @param scene the scene where the event occurred
  41597. * @param evt {Event} The original (browser) event
  41598. */
  41599. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41600. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41601. };
  41602. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41603. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41604. };
  41605. return ActionEvent;
  41606. }());
  41607. BABYLON.ActionEvent = ActionEvent;
  41608. /**
  41609. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41610. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41611. */
  41612. var ActionManager = /** @class */ (function () {
  41613. function ActionManager(scene) {
  41614. // Members
  41615. this.actions = new Array();
  41616. this.hoverCursor = '';
  41617. this._scene = scene;
  41618. scene._actionManagers.push(this);
  41619. }
  41620. Object.defineProperty(ActionManager, "NothingTrigger", {
  41621. get: function () {
  41622. return ActionManager._NothingTrigger;
  41623. },
  41624. enumerable: true,
  41625. configurable: true
  41626. });
  41627. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41628. get: function () {
  41629. return ActionManager._OnPickTrigger;
  41630. },
  41631. enumerable: true,
  41632. configurable: true
  41633. });
  41634. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41635. get: function () {
  41636. return ActionManager._OnLeftPickTrigger;
  41637. },
  41638. enumerable: true,
  41639. configurable: true
  41640. });
  41641. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41642. get: function () {
  41643. return ActionManager._OnRightPickTrigger;
  41644. },
  41645. enumerable: true,
  41646. configurable: true
  41647. });
  41648. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41649. get: function () {
  41650. return ActionManager._OnCenterPickTrigger;
  41651. },
  41652. enumerable: true,
  41653. configurable: true
  41654. });
  41655. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41656. get: function () {
  41657. return ActionManager._OnPickDownTrigger;
  41658. },
  41659. enumerable: true,
  41660. configurable: true
  41661. });
  41662. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41663. get: function () {
  41664. return ActionManager._OnDoublePickTrigger;
  41665. },
  41666. enumerable: true,
  41667. configurable: true
  41668. });
  41669. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41670. get: function () {
  41671. return ActionManager._OnPickUpTrigger;
  41672. },
  41673. enumerable: true,
  41674. configurable: true
  41675. });
  41676. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41677. /// This trigger will only be raised if you also declared a OnPickDown
  41678. get: function () {
  41679. return ActionManager._OnPickOutTrigger;
  41680. },
  41681. enumerable: true,
  41682. configurable: true
  41683. });
  41684. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41685. get: function () {
  41686. return ActionManager._OnLongPressTrigger;
  41687. },
  41688. enumerable: true,
  41689. configurable: true
  41690. });
  41691. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41692. get: function () {
  41693. return ActionManager._OnPointerOverTrigger;
  41694. },
  41695. enumerable: true,
  41696. configurable: true
  41697. });
  41698. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41699. get: function () {
  41700. return ActionManager._OnPointerOutTrigger;
  41701. },
  41702. enumerable: true,
  41703. configurable: true
  41704. });
  41705. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41706. get: function () {
  41707. return ActionManager._OnEveryFrameTrigger;
  41708. },
  41709. enumerable: true,
  41710. configurable: true
  41711. });
  41712. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41713. get: function () {
  41714. return ActionManager._OnIntersectionEnterTrigger;
  41715. },
  41716. enumerable: true,
  41717. configurable: true
  41718. });
  41719. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41720. get: function () {
  41721. return ActionManager._OnIntersectionExitTrigger;
  41722. },
  41723. enumerable: true,
  41724. configurable: true
  41725. });
  41726. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41727. get: function () {
  41728. return ActionManager._OnKeyDownTrigger;
  41729. },
  41730. enumerable: true,
  41731. configurable: true
  41732. });
  41733. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41734. get: function () {
  41735. return ActionManager._OnKeyUpTrigger;
  41736. },
  41737. enumerable: true,
  41738. configurable: true
  41739. });
  41740. // Methods
  41741. ActionManager.prototype.dispose = function () {
  41742. var index = this._scene._actionManagers.indexOf(this);
  41743. for (var i = 0; i < this.actions.length; i++) {
  41744. var action = this.actions[i];
  41745. ActionManager.Triggers[action.trigger]--;
  41746. if (ActionManager.Triggers[action.trigger] === 0) {
  41747. delete ActionManager.Triggers[action.trigger];
  41748. }
  41749. }
  41750. if (index > -1) {
  41751. this._scene._actionManagers.splice(index, 1);
  41752. }
  41753. };
  41754. ActionManager.prototype.getScene = function () {
  41755. return this._scene;
  41756. };
  41757. /**
  41758. * Does this action manager handles actions of any of the given triggers
  41759. * @param {number[]} triggers - the triggers to be tested
  41760. * @return {boolean} whether one (or more) of the triggers is handeled
  41761. */
  41762. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41763. for (var index = 0; index < this.actions.length; index++) {
  41764. var action = this.actions[index];
  41765. if (triggers.indexOf(action.trigger) > -1) {
  41766. return true;
  41767. }
  41768. }
  41769. return false;
  41770. };
  41771. /**
  41772. * Does this action manager handles actions of a given trigger
  41773. * @param {number} trigger - the trigger to be tested
  41774. * @return {boolean} whether the trigger is handeled
  41775. */
  41776. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41777. for (var index = 0; index < this.actions.length; index++) {
  41778. var action = this.actions[index];
  41779. if (action.trigger === trigger) {
  41780. return true;
  41781. }
  41782. }
  41783. return false;
  41784. };
  41785. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41786. /**
  41787. * Does this action manager has pointer triggers
  41788. * @return {boolean} whether or not it has pointer triggers
  41789. */
  41790. get: function () {
  41791. for (var index = 0; index < this.actions.length; index++) {
  41792. var action = this.actions[index];
  41793. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41794. return true;
  41795. }
  41796. }
  41797. return false;
  41798. },
  41799. enumerable: true,
  41800. configurable: true
  41801. });
  41802. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41803. /**
  41804. * Does this action manager has pick triggers
  41805. * @return {boolean} whether or not it has pick triggers
  41806. */
  41807. get: function () {
  41808. for (var index = 0; index < this.actions.length; index++) {
  41809. var action = this.actions[index];
  41810. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41811. return true;
  41812. }
  41813. }
  41814. return false;
  41815. },
  41816. enumerable: true,
  41817. configurable: true
  41818. });
  41819. Object.defineProperty(ActionManager, "HasTriggers", {
  41820. /**
  41821. * Does exist one action manager with at least one trigger
  41822. * @return {boolean} whether or not it exists one action manager with one trigger
  41823. **/
  41824. get: function () {
  41825. for (var t in ActionManager.Triggers) {
  41826. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41827. return true;
  41828. }
  41829. }
  41830. return false;
  41831. },
  41832. enumerable: true,
  41833. configurable: true
  41834. });
  41835. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41836. /**
  41837. * Does exist one action manager with at least one pick trigger
  41838. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41839. **/
  41840. get: function () {
  41841. for (var t in ActionManager.Triggers) {
  41842. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41843. var t_int = parseInt(t);
  41844. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41845. return true;
  41846. }
  41847. }
  41848. }
  41849. return false;
  41850. },
  41851. enumerable: true,
  41852. configurable: true
  41853. });
  41854. /**
  41855. * Does exist one action manager that handles actions of a given trigger
  41856. * @param {number} trigger - the trigger to be tested
  41857. * @return {boolean} whether the trigger is handeled by at least one action manager
  41858. **/
  41859. ActionManager.HasSpecificTrigger = function (trigger) {
  41860. for (var t in ActionManager.Triggers) {
  41861. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41862. var t_int = parseInt(t);
  41863. if (t_int === trigger) {
  41864. return true;
  41865. }
  41866. }
  41867. }
  41868. return false;
  41869. };
  41870. /**
  41871. * Registers an action to this action manager
  41872. * @param {BABYLON.Action} action - the action to be registered
  41873. * @return {BABYLON.Action} the action amended (prepared) after registration
  41874. */
  41875. ActionManager.prototype.registerAction = function (action) {
  41876. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41877. if (this.getScene().actionManager !== this) {
  41878. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41879. return null;
  41880. }
  41881. }
  41882. this.actions.push(action);
  41883. if (ActionManager.Triggers[action.trigger]) {
  41884. ActionManager.Triggers[action.trigger]++;
  41885. }
  41886. else {
  41887. ActionManager.Triggers[action.trigger] = 1;
  41888. }
  41889. action._actionManager = this;
  41890. action._prepare();
  41891. return action;
  41892. };
  41893. /**
  41894. * Process a specific trigger
  41895. * @param {number} trigger - the trigger to process
  41896. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41897. */
  41898. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41899. for (var index = 0; index < this.actions.length; index++) {
  41900. var action = this.actions[index];
  41901. if (action.trigger === trigger) {
  41902. if (evt) {
  41903. if (trigger === ActionManager.OnKeyUpTrigger
  41904. || trigger === ActionManager.OnKeyDownTrigger) {
  41905. var parameter = action.getTriggerParameter();
  41906. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41907. if (!parameter.toLowerCase) {
  41908. continue;
  41909. }
  41910. var lowerCase = parameter.toLowerCase();
  41911. if (lowerCase !== evt.sourceEvent.key) {
  41912. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41913. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41914. if (actualkey !== lowerCase) {
  41915. continue;
  41916. }
  41917. }
  41918. }
  41919. }
  41920. }
  41921. action._executeCurrent(evt);
  41922. }
  41923. }
  41924. };
  41925. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41926. var properties = propertyPath.split(".");
  41927. for (var index = 0; index < properties.length - 1; index++) {
  41928. target = target[properties[index]];
  41929. }
  41930. return target;
  41931. };
  41932. ActionManager.prototype._getProperty = function (propertyPath) {
  41933. var properties = propertyPath.split(".");
  41934. return properties[properties.length - 1];
  41935. };
  41936. ActionManager.prototype.serialize = function (name) {
  41937. var root = {
  41938. children: new Array(),
  41939. name: name,
  41940. type: 3,
  41941. properties: new Array() // Empty for root but required
  41942. };
  41943. for (var i = 0; i < this.actions.length; i++) {
  41944. var triggerObject = {
  41945. type: 0,
  41946. children: new Array(),
  41947. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41948. properties: new Array()
  41949. };
  41950. var triggerOptions = this.actions[i].triggerOptions;
  41951. if (triggerOptions && typeof triggerOptions !== "number") {
  41952. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41953. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  41954. }
  41955. else {
  41956. var parameter = {};
  41957. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  41958. if (triggerOptions.parameter.mesh) {
  41959. parameter._meshId = triggerOptions.parameter.mesh.id;
  41960. }
  41961. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  41962. }
  41963. }
  41964. // Serialize child action, recursively
  41965. this.actions[i].serialize(triggerObject);
  41966. // Add serialized trigger
  41967. root.children.push(triggerObject);
  41968. }
  41969. return root;
  41970. };
  41971. ActionManager.Parse = function (parsedActions, object, scene) {
  41972. var actionManager = new BABYLON.ActionManager(scene);
  41973. if (object === null)
  41974. scene.actionManager = actionManager;
  41975. else
  41976. object.actionManager = actionManager;
  41977. // instanciate a new object
  41978. var instanciate = function (name, params) {
  41979. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  41980. newInstance.constructor.apply(newInstance, params);
  41981. return newInstance;
  41982. };
  41983. var parseParameter = function (name, value, target, propertyPath) {
  41984. if (propertyPath === null) {
  41985. // String, boolean or float
  41986. var floatValue = parseFloat(value);
  41987. if (value === "true" || value === "false")
  41988. return value === "true";
  41989. else
  41990. return isNaN(floatValue) ? value : floatValue;
  41991. }
  41992. var effectiveTarget = propertyPath.split(".");
  41993. var values = value.split(",");
  41994. // Get effective Target
  41995. for (var i = 0; i < effectiveTarget.length; i++) {
  41996. target = target[effectiveTarget[i]];
  41997. }
  41998. // Return appropriate value with its type
  41999. if (typeof (target) === "boolean")
  42000. return values[0] === "true";
  42001. if (typeof (target) === "string")
  42002. return values[0];
  42003. // Parameters with multiple values such as Vector3 etc.
  42004. var split = new Array();
  42005. for (var i = 0; i < values.length; i++)
  42006. split.push(parseFloat(values[i]));
  42007. if (target instanceof BABYLON.Vector3)
  42008. return BABYLON.Vector3.FromArray(split);
  42009. if (target instanceof BABYLON.Vector4)
  42010. return BABYLON.Vector4.FromArray(split);
  42011. if (target instanceof BABYLON.Color3)
  42012. return BABYLON.Color3.FromArray(split);
  42013. if (target instanceof BABYLON.Color4)
  42014. return BABYLON.Color4.FromArray(split);
  42015. return parseFloat(values[0]);
  42016. };
  42017. // traverse graph per trigger
  42018. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42019. if (combineArray === void 0) { combineArray = null; }
  42020. if (parsedAction.detached)
  42021. return;
  42022. var parameters = new Array();
  42023. var target = null;
  42024. var propertyPath = null;
  42025. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42026. // Parameters
  42027. if (parsedAction.type === 2)
  42028. parameters.push(actionManager);
  42029. else
  42030. parameters.push(trigger);
  42031. if (combine) {
  42032. var actions = new Array();
  42033. for (var j = 0; j < parsedAction.combine.length; j++) {
  42034. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42035. }
  42036. parameters.push(actions);
  42037. }
  42038. else {
  42039. for (var i = 0; i < parsedAction.properties.length; i++) {
  42040. var value = parsedAction.properties[i].value;
  42041. var name = parsedAction.properties[i].name;
  42042. var targetType = parsedAction.properties[i].targetType;
  42043. if (name === "target")
  42044. if (targetType !== null && targetType === "SceneProperties")
  42045. value = target = scene;
  42046. else
  42047. value = target = scene.getNodeByName(value);
  42048. else if (name === "parent")
  42049. value = scene.getNodeByName(value);
  42050. else if (name === "sound")
  42051. value = scene.getSoundByName(value);
  42052. else if (name !== "propertyPath") {
  42053. if (parsedAction.type === 2 && name === "operator")
  42054. value = BABYLON.ValueCondition[value];
  42055. else
  42056. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42057. }
  42058. else {
  42059. propertyPath = value;
  42060. }
  42061. parameters.push(value);
  42062. }
  42063. }
  42064. if (combineArray === null) {
  42065. parameters.push(condition);
  42066. }
  42067. else {
  42068. parameters.push(null);
  42069. }
  42070. // If interpolate value action
  42071. if (parsedAction.name === "InterpolateValueAction") {
  42072. var param = parameters[parameters.length - 2];
  42073. parameters[parameters.length - 1] = param;
  42074. parameters[parameters.length - 2] = condition;
  42075. }
  42076. // Action or condition(s) and not CombineAction
  42077. var newAction = instanciate(parsedAction.name, parameters);
  42078. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42079. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42080. if (action)
  42081. action.then(nothing);
  42082. else
  42083. actionManager.registerAction(nothing);
  42084. action = nothing;
  42085. }
  42086. if (combineArray === null) {
  42087. if (newAction instanceof BABYLON.Condition) {
  42088. condition = newAction;
  42089. newAction = action;
  42090. }
  42091. else {
  42092. condition = null;
  42093. if (action)
  42094. action.then(newAction);
  42095. else
  42096. actionManager.registerAction(newAction);
  42097. }
  42098. }
  42099. else {
  42100. combineArray.push(newAction);
  42101. }
  42102. for (var i = 0; i < parsedAction.children.length; i++)
  42103. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42104. };
  42105. // triggers
  42106. for (var i = 0; i < parsedActions.children.length; i++) {
  42107. var triggerParams;
  42108. var trigger = parsedActions.children[i];
  42109. if (trigger.properties.length > 0) {
  42110. var param = trigger.properties[0].value;
  42111. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42112. if (value._meshId) {
  42113. value.mesh = scene.getMeshByID(value._meshId);
  42114. }
  42115. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42116. }
  42117. else
  42118. triggerParams = ActionManager[trigger.name];
  42119. for (var j = 0; j < trigger.children.length; j++) {
  42120. if (!trigger.detached)
  42121. traverse(trigger.children[j], triggerParams, null, null);
  42122. }
  42123. }
  42124. };
  42125. ActionManager.GetTriggerName = function (trigger) {
  42126. switch (trigger) {
  42127. case 0: return "NothingTrigger";
  42128. case 1: return "OnPickTrigger";
  42129. case 2: return "OnLeftPickTrigger";
  42130. case 3: return "OnRightPickTrigger";
  42131. case 4: return "OnCenterPickTrigger";
  42132. case 5: return "OnPickDownTrigger";
  42133. case 6: return "OnPickUpTrigger";
  42134. case 7: return "OnLongPressTrigger";
  42135. case 8: return "OnPointerOverTrigger";
  42136. case 9: return "OnPointerOutTrigger";
  42137. case 10: return "OnEveryFrameTrigger";
  42138. case 11: return "OnIntersectionEnterTrigger";
  42139. case 12: return "OnIntersectionExitTrigger";
  42140. case 13: return "OnKeyDownTrigger";
  42141. case 14: return "OnKeyUpTrigger";
  42142. case 15: return "OnPickOutTrigger";
  42143. default: return "";
  42144. }
  42145. };
  42146. // Statics
  42147. ActionManager._NothingTrigger = 0;
  42148. ActionManager._OnPickTrigger = 1;
  42149. ActionManager._OnLeftPickTrigger = 2;
  42150. ActionManager._OnRightPickTrigger = 3;
  42151. ActionManager._OnCenterPickTrigger = 4;
  42152. ActionManager._OnPickDownTrigger = 5;
  42153. ActionManager._OnDoublePickTrigger = 6;
  42154. ActionManager._OnPickUpTrigger = 7;
  42155. ActionManager._OnLongPressTrigger = 8;
  42156. ActionManager._OnPointerOverTrigger = 9;
  42157. ActionManager._OnPointerOutTrigger = 10;
  42158. ActionManager._OnEveryFrameTrigger = 11;
  42159. ActionManager._OnIntersectionEnterTrigger = 12;
  42160. ActionManager._OnIntersectionExitTrigger = 13;
  42161. ActionManager._OnKeyDownTrigger = 14;
  42162. ActionManager._OnKeyUpTrigger = 15;
  42163. ActionManager._OnPickOutTrigger = 16;
  42164. ActionManager.Triggers = {};
  42165. return ActionManager;
  42166. }());
  42167. BABYLON.ActionManager = ActionManager;
  42168. })(BABYLON || (BABYLON = {}));
  42169. //# sourceMappingURL=babylon.actionManager.js.map
  42170. var BABYLON;
  42171. (function (BABYLON) {
  42172. var InterpolateValueAction = /** @class */ (function (_super) {
  42173. __extends(InterpolateValueAction, _super);
  42174. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42175. if (duration === void 0) { duration = 1000; }
  42176. var _this = _super.call(this, triggerOptions, condition) || this;
  42177. _this.propertyPath = propertyPath;
  42178. _this.value = value;
  42179. _this.duration = duration;
  42180. _this.stopOtherAnimations = stopOtherAnimations;
  42181. _this.onInterpolationDone = onInterpolationDone;
  42182. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42183. _this._target = _this._effectiveTarget = target;
  42184. return _this;
  42185. }
  42186. InterpolateValueAction.prototype._prepare = function () {
  42187. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42188. this._property = this._getProperty(this.propertyPath);
  42189. };
  42190. InterpolateValueAction.prototype.execute = function () {
  42191. var _this = this;
  42192. var scene = this._actionManager.getScene();
  42193. var keys = [
  42194. {
  42195. frame: 0,
  42196. value: this._effectiveTarget[this._property]
  42197. }, {
  42198. frame: 100,
  42199. value: this.value
  42200. }
  42201. ];
  42202. var dataType;
  42203. if (typeof this.value === "number") {
  42204. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42205. }
  42206. else if (this.value instanceof BABYLON.Color3) {
  42207. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42208. }
  42209. else if (this.value instanceof BABYLON.Vector3) {
  42210. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42211. }
  42212. else if (this.value instanceof BABYLON.Matrix) {
  42213. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42214. }
  42215. else if (this.value instanceof BABYLON.Quaternion) {
  42216. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42217. }
  42218. else {
  42219. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42220. return;
  42221. }
  42222. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42223. animation.setKeys(keys);
  42224. if (this.stopOtherAnimations) {
  42225. scene.stopAnimation(this._effectiveTarget);
  42226. }
  42227. var wrapper = function () {
  42228. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42229. if (_this.onInterpolationDone) {
  42230. _this.onInterpolationDone();
  42231. }
  42232. };
  42233. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42234. };
  42235. InterpolateValueAction.prototype.serialize = function (parent) {
  42236. return _super.prototype._serialize.call(this, {
  42237. name: "InterpolateValueAction",
  42238. properties: [
  42239. BABYLON.Action._GetTargetProperty(this._target),
  42240. { name: "propertyPath", value: this.propertyPath },
  42241. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42242. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42243. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42244. ]
  42245. }, parent);
  42246. };
  42247. return InterpolateValueAction;
  42248. }(BABYLON.Action));
  42249. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42250. })(BABYLON || (BABYLON = {}));
  42251. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42252. var BABYLON;
  42253. (function (BABYLON) {
  42254. var SwitchBooleanAction = /** @class */ (function (_super) {
  42255. __extends(SwitchBooleanAction, _super);
  42256. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42257. var _this = _super.call(this, triggerOptions, condition) || this;
  42258. _this.propertyPath = propertyPath;
  42259. _this._target = _this._effectiveTarget = target;
  42260. return _this;
  42261. }
  42262. SwitchBooleanAction.prototype._prepare = function () {
  42263. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42264. this._property = this._getProperty(this.propertyPath);
  42265. };
  42266. SwitchBooleanAction.prototype.execute = function () {
  42267. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42268. };
  42269. SwitchBooleanAction.prototype.serialize = function (parent) {
  42270. return _super.prototype._serialize.call(this, {
  42271. name: "SwitchBooleanAction",
  42272. properties: [
  42273. BABYLON.Action._GetTargetProperty(this._target),
  42274. { name: "propertyPath", value: this.propertyPath }
  42275. ]
  42276. }, parent);
  42277. };
  42278. return SwitchBooleanAction;
  42279. }(BABYLON.Action));
  42280. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42281. var SetStateAction = /** @class */ (function (_super) {
  42282. __extends(SetStateAction, _super);
  42283. function SetStateAction(triggerOptions, target, value, condition) {
  42284. var _this = _super.call(this, triggerOptions, condition) || this;
  42285. _this.value = value;
  42286. _this._target = target;
  42287. return _this;
  42288. }
  42289. SetStateAction.prototype.execute = function () {
  42290. this._target.state = this.value;
  42291. };
  42292. SetStateAction.prototype.serialize = function (parent) {
  42293. return _super.prototype._serialize.call(this, {
  42294. name: "SetStateAction",
  42295. properties: [
  42296. BABYLON.Action._GetTargetProperty(this._target),
  42297. { name: "value", value: this.value }
  42298. ]
  42299. }, parent);
  42300. };
  42301. return SetStateAction;
  42302. }(BABYLON.Action));
  42303. BABYLON.SetStateAction = SetStateAction;
  42304. var SetValueAction = /** @class */ (function (_super) {
  42305. __extends(SetValueAction, _super);
  42306. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42307. var _this = _super.call(this, triggerOptions, condition) || this;
  42308. _this.propertyPath = propertyPath;
  42309. _this.value = value;
  42310. _this._target = _this._effectiveTarget = target;
  42311. return _this;
  42312. }
  42313. SetValueAction.prototype._prepare = function () {
  42314. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42315. this._property = this._getProperty(this.propertyPath);
  42316. };
  42317. SetValueAction.prototype.execute = function () {
  42318. this._effectiveTarget[this._property] = this.value;
  42319. if (this._target.markAsDirty) {
  42320. this._target.markAsDirty(this._property);
  42321. }
  42322. };
  42323. SetValueAction.prototype.serialize = function (parent) {
  42324. return _super.prototype._serialize.call(this, {
  42325. name: "SetValueAction",
  42326. properties: [
  42327. BABYLON.Action._GetTargetProperty(this._target),
  42328. { name: "propertyPath", value: this.propertyPath },
  42329. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42330. ]
  42331. }, parent);
  42332. };
  42333. return SetValueAction;
  42334. }(BABYLON.Action));
  42335. BABYLON.SetValueAction = SetValueAction;
  42336. var IncrementValueAction = /** @class */ (function (_super) {
  42337. __extends(IncrementValueAction, _super);
  42338. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42339. var _this = _super.call(this, triggerOptions, condition) || this;
  42340. _this.propertyPath = propertyPath;
  42341. _this.value = value;
  42342. _this._target = _this._effectiveTarget = target;
  42343. return _this;
  42344. }
  42345. IncrementValueAction.prototype._prepare = function () {
  42346. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42347. this._property = this._getProperty(this.propertyPath);
  42348. if (typeof this._effectiveTarget[this._property] !== "number") {
  42349. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42350. }
  42351. };
  42352. IncrementValueAction.prototype.execute = function () {
  42353. this._effectiveTarget[this._property] += this.value;
  42354. if (this._target.markAsDirty) {
  42355. this._target.markAsDirty(this._property);
  42356. }
  42357. };
  42358. IncrementValueAction.prototype.serialize = function (parent) {
  42359. return _super.prototype._serialize.call(this, {
  42360. name: "IncrementValueAction",
  42361. properties: [
  42362. BABYLON.Action._GetTargetProperty(this._target),
  42363. { name: "propertyPath", value: this.propertyPath },
  42364. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42365. ]
  42366. }, parent);
  42367. };
  42368. return IncrementValueAction;
  42369. }(BABYLON.Action));
  42370. BABYLON.IncrementValueAction = IncrementValueAction;
  42371. var PlayAnimationAction = /** @class */ (function (_super) {
  42372. __extends(PlayAnimationAction, _super);
  42373. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42374. var _this = _super.call(this, triggerOptions, condition) || this;
  42375. _this.from = from;
  42376. _this.to = to;
  42377. _this.loop = loop;
  42378. _this._target = target;
  42379. return _this;
  42380. }
  42381. PlayAnimationAction.prototype._prepare = function () {
  42382. };
  42383. PlayAnimationAction.prototype.execute = function () {
  42384. var scene = this._actionManager.getScene();
  42385. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42386. };
  42387. PlayAnimationAction.prototype.serialize = function (parent) {
  42388. return _super.prototype._serialize.call(this, {
  42389. name: "PlayAnimationAction",
  42390. properties: [
  42391. BABYLON.Action._GetTargetProperty(this._target),
  42392. { name: "from", value: String(this.from) },
  42393. { name: "to", value: String(this.to) },
  42394. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42395. ]
  42396. }, parent);
  42397. };
  42398. return PlayAnimationAction;
  42399. }(BABYLON.Action));
  42400. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42401. var StopAnimationAction = /** @class */ (function (_super) {
  42402. __extends(StopAnimationAction, _super);
  42403. function StopAnimationAction(triggerOptions, target, condition) {
  42404. var _this = _super.call(this, triggerOptions, condition) || this;
  42405. _this._target = target;
  42406. return _this;
  42407. }
  42408. StopAnimationAction.prototype._prepare = function () {
  42409. };
  42410. StopAnimationAction.prototype.execute = function () {
  42411. var scene = this._actionManager.getScene();
  42412. scene.stopAnimation(this._target);
  42413. };
  42414. StopAnimationAction.prototype.serialize = function (parent) {
  42415. return _super.prototype._serialize.call(this, {
  42416. name: "StopAnimationAction",
  42417. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42418. }, parent);
  42419. };
  42420. return StopAnimationAction;
  42421. }(BABYLON.Action));
  42422. BABYLON.StopAnimationAction = StopAnimationAction;
  42423. var DoNothingAction = /** @class */ (function (_super) {
  42424. __extends(DoNothingAction, _super);
  42425. function DoNothingAction(triggerOptions, condition) {
  42426. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42427. return _super.call(this, triggerOptions, condition) || this;
  42428. }
  42429. DoNothingAction.prototype.execute = function () {
  42430. };
  42431. DoNothingAction.prototype.serialize = function (parent) {
  42432. return _super.prototype._serialize.call(this, {
  42433. name: "DoNothingAction",
  42434. properties: []
  42435. }, parent);
  42436. };
  42437. return DoNothingAction;
  42438. }(BABYLON.Action));
  42439. BABYLON.DoNothingAction = DoNothingAction;
  42440. var CombineAction = /** @class */ (function (_super) {
  42441. __extends(CombineAction, _super);
  42442. function CombineAction(triggerOptions, children, condition) {
  42443. var _this = _super.call(this, triggerOptions, condition) || this;
  42444. _this.children = children;
  42445. return _this;
  42446. }
  42447. CombineAction.prototype._prepare = function () {
  42448. for (var index = 0; index < this.children.length; index++) {
  42449. this.children[index]._actionManager = this._actionManager;
  42450. this.children[index]._prepare();
  42451. }
  42452. };
  42453. CombineAction.prototype.execute = function (evt) {
  42454. for (var index = 0; index < this.children.length; index++) {
  42455. this.children[index].execute(evt);
  42456. }
  42457. };
  42458. CombineAction.prototype.serialize = function (parent) {
  42459. var serializationObject = _super.prototype._serialize.call(this, {
  42460. name: "CombineAction",
  42461. properties: [],
  42462. combine: []
  42463. }, parent);
  42464. for (var i = 0; i < this.children.length; i++) {
  42465. serializationObject.combine.push(this.children[i].serialize(null));
  42466. }
  42467. return serializationObject;
  42468. };
  42469. return CombineAction;
  42470. }(BABYLON.Action));
  42471. BABYLON.CombineAction = CombineAction;
  42472. var ExecuteCodeAction = /** @class */ (function (_super) {
  42473. __extends(ExecuteCodeAction, _super);
  42474. function ExecuteCodeAction(triggerOptions, func, condition) {
  42475. var _this = _super.call(this, triggerOptions, condition) || this;
  42476. _this.func = func;
  42477. return _this;
  42478. }
  42479. ExecuteCodeAction.prototype.execute = function (evt) {
  42480. this.func(evt);
  42481. };
  42482. return ExecuteCodeAction;
  42483. }(BABYLON.Action));
  42484. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42485. var SetParentAction = /** @class */ (function (_super) {
  42486. __extends(SetParentAction, _super);
  42487. function SetParentAction(triggerOptions, target, parent, condition) {
  42488. var _this = _super.call(this, triggerOptions, condition) || this;
  42489. _this._target = target;
  42490. _this._parent = parent;
  42491. return _this;
  42492. }
  42493. SetParentAction.prototype._prepare = function () {
  42494. };
  42495. SetParentAction.prototype.execute = function () {
  42496. if (this._target.parent === this._parent) {
  42497. return;
  42498. }
  42499. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42500. invertParentWorldMatrix.invert();
  42501. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42502. this._target.parent = this._parent;
  42503. };
  42504. SetParentAction.prototype.serialize = function (parent) {
  42505. return _super.prototype._serialize.call(this, {
  42506. name: "SetParentAction",
  42507. properties: [
  42508. BABYLON.Action._GetTargetProperty(this._target),
  42509. BABYLON.Action._GetTargetProperty(this._parent),
  42510. ]
  42511. }, parent);
  42512. };
  42513. return SetParentAction;
  42514. }(BABYLON.Action));
  42515. BABYLON.SetParentAction = SetParentAction;
  42516. var PlaySoundAction = /** @class */ (function (_super) {
  42517. __extends(PlaySoundAction, _super);
  42518. function PlaySoundAction(triggerOptions, sound, condition) {
  42519. var _this = _super.call(this, triggerOptions, condition) || this;
  42520. _this._sound = sound;
  42521. return _this;
  42522. }
  42523. PlaySoundAction.prototype._prepare = function () {
  42524. };
  42525. PlaySoundAction.prototype.execute = function () {
  42526. if (this._sound !== undefined)
  42527. this._sound.play();
  42528. };
  42529. PlaySoundAction.prototype.serialize = function (parent) {
  42530. return _super.prototype._serialize.call(this, {
  42531. name: "PlaySoundAction",
  42532. properties: [{ name: "sound", value: this._sound.name }]
  42533. }, parent);
  42534. };
  42535. return PlaySoundAction;
  42536. }(BABYLON.Action));
  42537. BABYLON.PlaySoundAction = PlaySoundAction;
  42538. var StopSoundAction = /** @class */ (function (_super) {
  42539. __extends(StopSoundAction, _super);
  42540. function StopSoundAction(triggerOptions, sound, condition) {
  42541. var _this = _super.call(this, triggerOptions, condition) || this;
  42542. _this._sound = sound;
  42543. return _this;
  42544. }
  42545. StopSoundAction.prototype._prepare = function () {
  42546. };
  42547. StopSoundAction.prototype.execute = function () {
  42548. if (this._sound !== undefined)
  42549. this._sound.stop();
  42550. };
  42551. StopSoundAction.prototype.serialize = function (parent) {
  42552. return _super.prototype._serialize.call(this, {
  42553. name: "StopSoundAction",
  42554. properties: [{ name: "sound", value: this._sound.name }]
  42555. }, parent);
  42556. };
  42557. return StopSoundAction;
  42558. }(BABYLON.Action));
  42559. BABYLON.StopSoundAction = StopSoundAction;
  42560. })(BABYLON || (BABYLON = {}));
  42561. //# sourceMappingURL=babylon.directActions.js.map
  42562. var BABYLON;
  42563. (function (BABYLON) {
  42564. var SpriteManager = /** @class */ (function () {
  42565. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  42566. if (epsilon === void 0) { epsilon = 0.01; }
  42567. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42568. this.name = name;
  42569. this.sprites = new Array();
  42570. this.renderingGroupId = 0;
  42571. this.layerMask = 0x0FFFFFFF;
  42572. this.fogEnabled = true;
  42573. this.isPickable = false;
  42574. /**
  42575. * An event triggered when the manager is disposed.
  42576. * @type {BABYLON.Observable}
  42577. */
  42578. this.onDisposeObservable = new BABYLON.Observable();
  42579. this._vertexBuffers = {};
  42580. this._capacity = capacity;
  42581. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  42582. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42583. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42584. if (cellSize.width && cellSize.height) {
  42585. this.cellWidth = cellSize.width;
  42586. this.cellHeight = cellSize.height;
  42587. }
  42588. else if (cellSize !== undefined) {
  42589. this.cellWidth = cellSize;
  42590. this.cellHeight = cellSize;
  42591. }
  42592. else {
  42593. return;
  42594. }
  42595. this._epsilon = epsilon;
  42596. this._scene = scene;
  42597. this._scene.spriteManagers.push(this);
  42598. var indices = [];
  42599. var index = 0;
  42600. for (var count = 0; count < capacity; count++) {
  42601. indices.push(index);
  42602. indices.push(index + 1);
  42603. indices.push(index + 2);
  42604. indices.push(index);
  42605. indices.push(index + 2);
  42606. indices.push(index + 3);
  42607. index += 4;
  42608. }
  42609. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  42610. // VBO
  42611. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  42612. this._vertexData = new Float32Array(capacity * 16 * 4);
  42613. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  42614. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  42615. var options = this._buffer.createVertexBuffer("options", 4, 4);
  42616. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  42617. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  42618. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42619. this._vertexBuffers["options"] = options;
  42620. this._vertexBuffers["cellInfo"] = cellInfo;
  42621. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42622. // Effects
  42623. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  42624. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  42625. }
  42626. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  42627. set: function (callback) {
  42628. if (this._onDisposeObserver) {
  42629. this.onDisposeObservable.remove(this._onDisposeObserver);
  42630. }
  42631. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42632. },
  42633. enumerable: true,
  42634. configurable: true
  42635. });
  42636. Object.defineProperty(SpriteManager.prototype, "texture", {
  42637. get: function () {
  42638. return this._spriteTexture;
  42639. },
  42640. set: function (value) {
  42641. this._spriteTexture = value;
  42642. },
  42643. enumerable: true,
  42644. configurable: true
  42645. });
  42646. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  42647. var arrayOffset = index * 16;
  42648. if (offsetX === 0)
  42649. offsetX = this._epsilon;
  42650. else if (offsetX === 1)
  42651. offsetX = 1 - this._epsilon;
  42652. if (offsetY === 0)
  42653. offsetY = this._epsilon;
  42654. else if (offsetY === 1)
  42655. offsetY = 1 - this._epsilon;
  42656. this._vertexData[arrayOffset] = sprite.position.x;
  42657. this._vertexData[arrayOffset + 1] = sprite.position.y;
  42658. this._vertexData[arrayOffset + 2] = sprite.position.z;
  42659. this._vertexData[arrayOffset + 3] = sprite.angle;
  42660. this._vertexData[arrayOffset + 4] = sprite.width;
  42661. this._vertexData[arrayOffset + 5] = sprite.height;
  42662. this._vertexData[arrayOffset + 6] = offsetX;
  42663. this._vertexData[arrayOffset + 7] = offsetY;
  42664. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  42665. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  42666. var offset = (sprite.cellIndex / rowSize) >> 0;
  42667. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  42668. this._vertexData[arrayOffset + 11] = offset;
  42669. // Color
  42670. this._vertexData[arrayOffset + 12] = sprite.color.r;
  42671. this._vertexData[arrayOffset + 13] = sprite.color.g;
  42672. this._vertexData[arrayOffset + 14] = sprite.color.b;
  42673. this._vertexData[arrayOffset + 15] = sprite.color.a;
  42674. };
  42675. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  42676. var count = Math.min(this._capacity, this.sprites.length);
  42677. var min = BABYLON.Vector3.Zero();
  42678. var max = BABYLON.Vector3.Zero();
  42679. var distance = Number.MAX_VALUE;
  42680. var currentSprite = null;
  42681. var cameraSpacePosition = BABYLON.Vector3.Zero();
  42682. var cameraView = camera.getViewMatrix();
  42683. for (var index = 0; index < count; index++) {
  42684. var sprite = this.sprites[index];
  42685. if (!sprite) {
  42686. continue;
  42687. }
  42688. if (predicate) {
  42689. if (!predicate(sprite)) {
  42690. continue;
  42691. }
  42692. }
  42693. else if (!sprite.isPickable) {
  42694. continue;
  42695. }
  42696. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  42697. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  42698. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  42699. if (ray.intersectsBoxMinMax(min, max)) {
  42700. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  42701. if (distance > currentDistance) {
  42702. distance = currentDistance;
  42703. currentSprite = sprite;
  42704. if (fastCheck) {
  42705. break;
  42706. }
  42707. }
  42708. }
  42709. }
  42710. if (currentSprite) {
  42711. var result = new BABYLON.PickingInfo();
  42712. result.hit = true;
  42713. result.pickedSprite = currentSprite;
  42714. result.distance = distance;
  42715. return result;
  42716. }
  42717. return null;
  42718. };
  42719. SpriteManager.prototype.render = function () {
  42720. // Check
  42721. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  42722. return;
  42723. var engine = this._scene.getEngine();
  42724. var baseSize = this._spriteTexture.getBaseSize();
  42725. // Sprites
  42726. var deltaTime = engine.getDeltaTime();
  42727. var max = Math.min(this._capacity, this.sprites.length);
  42728. var rowSize = baseSize.width / this.cellWidth;
  42729. var offset = 0;
  42730. for (var index = 0; index < max; index++) {
  42731. var sprite = this.sprites[index];
  42732. if (!sprite) {
  42733. continue;
  42734. }
  42735. sprite._animate(deltaTime);
  42736. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  42737. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  42738. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  42739. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  42740. }
  42741. this._buffer.update(this._vertexData);
  42742. // Render
  42743. var effect = this._effectBase;
  42744. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42745. effect = this._effectFog;
  42746. }
  42747. engine.enableEffect(effect);
  42748. var viewMatrix = this._scene.getViewMatrix();
  42749. effect.setTexture("diffuseSampler", this._spriteTexture);
  42750. effect.setMatrix("view", viewMatrix);
  42751. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42752. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  42753. // Fog
  42754. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42755. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  42756. effect.setColor3("vFogColor", this._scene.fogColor);
  42757. }
  42758. // VBOs
  42759. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42760. // Draw order
  42761. engine.setDepthFunctionToLessOrEqual();
  42762. effect.setBool("alphaTest", true);
  42763. engine.setColorWrite(false);
  42764. engine.draw(true, 0, max * 6);
  42765. engine.setColorWrite(true);
  42766. effect.setBool("alphaTest", false);
  42767. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42768. engine.draw(true, 0, max * 6);
  42769. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42770. };
  42771. SpriteManager.prototype.dispose = function () {
  42772. if (this._buffer) {
  42773. this._buffer.dispose();
  42774. this._buffer = null;
  42775. }
  42776. if (this._indexBuffer) {
  42777. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42778. this._indexBuffer = null;
  42779. }
  42780. if (this._spriteTexture) {
  42781. this._spriteTexture.dispose();
  42782. this._spriteTexture = null;
  42783. }
  42784. // Remove from scene
  42785. var index = this._scene.spriteManagers.indexOf(this);
  42786. this._scene.spriteManagers.splice(index, 1);
  42787. // Callback
  42788. this.onDisposeObservable.notifyObservers(this);
  42789. this.onDisposeObservable.clear();
  42790. };
  42791. return SpriteManager;
  42792. }());
  42793. BABYLON.SpriteManager = SpriteManager;
  42794. })(BABYLON || (BABYLON = {}));
  42795. //# sourceMappingURL=babylon.spriteManager.js.map
  42796. var BABYLON;
  42797. (function (BABYLON) {
  42798. var Sprite = /** @class */ (function () {
  42799. function Sprite(name, manager) {
  42800. this.name = name;
  42801. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42802. this.width = 1.0;
  42803. this.height = 1.0;
  42804. this.angle = 0;
  42805. this.cellIndex = 0;
  42806. this.invertU = 0;
  42807. this.invertV = 0;
  42808. this.animations = new Array();
  42809. this.isPickable = false;
  42810. this._animationStarted = false;
  42811. this._loopAnimation = false;
  42812. this._fromIndex = 0;
  42813. this._toIndex = 0;
  42814. this._delay = 0;
  42815. this._direction = 1;
  42816. this._time = 0;
  42817. this._manager = manager;
  42818. this._manager.sprites.push(this);
  42819. this.position = BABYLON.Vector3.Zero();
  42820. }
  42821. Object.defineProperty(Sprite.prototype, "size", {
  42822. get: function () {
  42823. return this.width;
  42824. },
  42825. set: function (value) {
  42826. this.width = value;
  42827. this.height = value;
  42828. },
  42829. enumerable: true,
  42830. configurable: true
  42831. });
  42832. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  42833. this._fromIndex = from;
  42834. this._toIndex = to;
  42835. this._loopAnimation = loop;
  42836. this._delay = delay;
  42837. this._animationStarted = true;
  42838. this._direction = from < to ? 1 : -1;
  42839. this.cellIndex = from;
  42840. this._time = 0;
  42841. this._onAnimationEnd = onAnimationEnd;
  42842. };
  42843. Sprite.prototype.stopAnimation = function () {
  42844. this._animationStarted = false;
  42845. };
  42846. Sprite.prototype._animate = function (deltaTime) {
  42847. if (!this._animationStarted)
  42848. return;
  42849. this._time += deltaTime;
  42850. if (this._time > this._delay) {
  42851. this._time = this._time % this._delay;
  42852. this.cellIndex += this._direction;
  42853. if (this.cellIndex > this._toIndex) {
  42854. if (this._loopAnimation) {
  42855. this.cellIndex = this._fromIndex;
  42856. }
  42857. else {
  42858. this.cellIndex = this._toIndex;
  42859. this._animationStarted = false;
  42860. if (this._onAnimationEnd) {
  42861. this._onAnimationEnd();
  42862. }
  42863. if (this.disposeWhenFinishedAnimating) {
  42864. this.dispose();
  42865. }
  42866. }
  42867. }
  42868. }
  42869. };
  42870. Sprite.prototype.dispose = function () {
  42871. for (var i = 0; i < this._manager.sprites.length; i++) {
  42872. if (this._manager.sprites[i] == this) {
  42873. this._manager.sprites.splice(i, 1);
  42874. }
  42875. }
  42876. };
  42877. return Sprite;
  42878. }());
  42879. BABYLON.Sprite = Sprite;
  42880. })(BABYLON || (BABYLON = {}));
  42881. //# sourceMappingURL=babylon.sprite.js.map
  42882. var BABYLON;
  42883. (function (BABYLON) {
  42884. var IntersectionInfo = /** @class */ (function () {
  42885. function IntersectionInfo(bu, bv, distance) {
  42886. this.bu = bu;
  42887. this.bv = bv;
  42888. this.distance = distance;
  42889. this.faceId = 0;
  42890. this.subMeshId = 0;
  42891. }
  42892. return IntersectionInfo;
  42893. }());
  42894. BABYLON.IntersectionInfo = IntersectionInfo;
  42895. var PickingInfo = /** @class */ (function () {
  42896. function PickingInfo() {
  42897. this.hit = false;
  42898. this.distance = 0;
  42899. this.pickedPoint = null;
  42900. this.pickedMesh = null;
  42901. this.bu = 0;
  42902. this.bv = 0;
  42903. this.faceId = -1;
  42904. this.subMeshId = 0;
  42905. this.pickedSprite = null;
  42906. }
  42907. // Methods
  42908. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  42909. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  42910. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  42911. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42912. return null;
  42913. }
  42914. var indices = this.pickedMesh.getIndices();
  42915. if (!indices) {
  42916. return null;
  42917. }
  42918. var result;
  42919. if (useVerticesNormals) {
  42920. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42921. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  42922. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  42923. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  42924. normal0 = normal0.scale(this.bu);
  42925. normal1 = normal1.scale(this.bv);
  42926. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  42927. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  42928. }
  42929. else {
  42930. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42931. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  42932. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  42933. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  42934. var p1p2 = vertex1.subtract(vertex2);
  42935. var p3p2 = vertex3.subtract(vertex2);
  42936. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  42937. }
  42938. if (useWorldCoordinates) {
  42939. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  42940. }
  42941. return BABYLON.Vector3.Normalize(result);
  42942. };
  42943. PickingInfo.prototype.getTextureCoordinates = function () {
  42944. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42945. return null;
  42946. }
  42947. var indices = this.pickedMesh.getIndices();
  42948. if (!indices) {
  42949. return null;
  42950. }
  42951. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42952. if (!uvs) {
  42953. return null;
  42954. }
  42955. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  42956. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  42957. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  42958. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  42959. uv1 = uv1.scale(this.bu);
  42960. uv2 = uv2.scale(this.bv);
  42961. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  42962. };
  42963. return PickingInfo;
  42964. }());
  42965. BABYLON.PickingInfo = PickingInfo;
  42966. })(BABYLON || (BABYLON = {}));
  42967. //# sourceMappingURL=babylon.pickingInfo.js.map
  42968. var BABYLON;
  42969. (function (BABYLON) {
  42970. var Ray = /** @class */ (function () {
  42971. function Ray(origin, direction, length) {
  42972. if (length === void 0) { length = Number.MAX_VALUE; }
  42973. this.origin = origin;
  42974. this.direction = direction;
  42975. this.length = length;
  42976. }
  42977. // Methods
  42978. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  42979. var d = 0.0;
  42980. var maxValue = Number.MAX_VALUE;
  42981. var inv;
  42982. var min;
  42983. var max;
  42984. var temp;
  42985. if (Math.abs(this.direction.x) < 0.0000001) {
  42986. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  42987. return false;
  42988. }
  42989. }
  42990. else {
  42991. inv = 1.0 / this.direction.x;
  42992. min = (minimum.x - this.origin.x) * inv;
  42993. max = (maximum.x - this.origin.x) * inv;
  42994. if (max === -Infinity) {
  42995. max = Infinity;
  42996. }
  42997. if (min > max) {
  42998. temp = min;
  42999. min = max;
  43000. max = temp;
  43001. }
  43002. d = Math.max(min, d);
  43003. maxValue = Math.min(max, maxValue);
  43004. if (d > maxValue) {
  43005. return false;
  43006. }
  43007. }
  43008. if (Math.abs(this.direction.y) < 0.0000001) {
  43009. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  43010. return false;
  43011. }
  43012. }
  43013. else {
  43014. inv = 1.0 / this.direction.y;
  43015. min = (minimum.y - this.origin.y) * inv;
  43016. max = (maximum.y - this.origin.y) * inv;
  43017. if (max === -Infinity) {
  43018. max = Infinity;
  43019. }
  43020. if (min > max) {
  43021. temp = min;
  43022. min = max;
  43023. max = temp;
  43024. }
  43025. d = Math.max(min, d);
  43026. maxValue = Math.min(max, maxValue);
  43027. if (d > maxValue) {
  43028. return false;
  43029. }
  43030. }
  43031. if (Math.abs(this.direction.z) < 0.0000001) {
  43032. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  43033. return false;
  43034. }
  43035. }
  43036. else {
  43037. inv = 1.0 / this.direction.z;
  43038. min = (minimum.z - this.origin.z) * inv;
  43039. max = (maximum.z - this.origin.z) * inv;
  43040. if (max === -Infinity) {
  43041. max = Infinity;
  43042. }
  43043. if (min > max) {
  43044. temp = min;
  43045. min = max;
  43046. max = temp;
  43047. }
  43048. d = Math.max(min, d);
  43049. maxValue = Math.min(max, maxValue);
  43050. if (d > maxValue) {
  43051. return false;
  43052. }
  43053. }
  43054. return true;
  43055. };
  43056. Ray.prototype.intersectsBox = function (box) {
  43057. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  43058. };
  43059. Ray.prototype.intersectsSphere = function (sphere) {
  43060. var x = sphere.center.x - this.origin.x;
  43061. var y = sphere.center.y - this.origin.y;
  43062. var z = sphere.center.z - this.origin.z;
  43063. var pyth = (x * x) + (y * y) + (z * z);
  43064. var rr = sphere.radius * sphere.radius;
  43065. if (pyth <= rr) {
  43066. return true;
  43067. }
  43068. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  43069. if (dot < 0.0) {
  43070. return false;
  43071. }
  43072. var temp = pyth - (dot * dot);
  43073. return temp <= rr;
  43074. };
  43075. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  43076. if (!this._edge1) {
  43077. this._edge1 = BABYLON.Vector3.Zero();
  43078. this._edge2 = BABYLON.Vector3.Zero();
  43079. this._pvec = BABYLON.Vector3.Zero();
  43080. this._tvec = BABYLON.Vector3.Zero();
  43081. this._qvec = BABYLON.Vector3.Zero();
  43082. }
  43083. vertex1.subtractToRef(vertex0, this._edge1);
  43084. vertex2.subtractToRef(vertex0, this._edge2);
  43085. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  43086. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43087. if (det === 0) {
  43088. return null;
  43089. }
  43090. var invdet = 1 / det;
  43091. this.origin.subtractToRef(vertex0, this._tvec);
  43092. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43093. if (bu < 0 || bu > 1.0) {
  43094. return null;
  43095. }
  43096. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43097. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43098. if (bv < 0 || bu + bv > 1.0) {
  43099. return null;
  43100. }
  43101. //check if the distance is longer than the predefined length.
  43102. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43103. if (distance > this.length) {
  43104. return null;
  43105. }
  43106. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43107. };
  43108. Ray.prototype.intersectsPlane = function (plane) {
  43109. var distance;
  43110. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43111. if (Math.abs(result1) < 9.99999997475243E-07) {
  43112. return null;
  43113. }
  43114. else {
  43115. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43116. distance = (-plane.d - result2) / result1;
  43117. if (distance < 0.0) {
  43118. if (distance < -9.99999997475243E-07) {
  43119. return null;
  43120. }
  43121. else {
  43122. return 0;
  43123. }
  43124. }
  43125. return distance;
  43126. }
  43127. };
  43128. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43129. var tm = BABYLON.Tmp.Matrix[0];
  43130. mesh.getWorldMatrix().invertToRef(tm);
  43131. if (this._tmpRay) {
  43132. Ray.TransformToRef(this, tm, this._tmpRay);
  43133. }
  43134. else {
  43135. this._tmpRay = Ray.Transform(this, tm);
  43136. }
  43137. return mesh.intersects(this._tmpRay, fastCheck);
  43138. };
  43139. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43140. if (results) {
  43141. results.length = 0;
  43142. }
  43143. else {
  43144. results = [];
  43145. }
  43146. for (var i = 0; i < meshes.length; i++) {
  43147. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43148. if (pickInfo.hit) {
  43149. results.push(pickInfo);
  43150. }
  43151. }
  43152. results.sort(this._comparePickingInfo);
  43153. return results;
  43154. };
  43155. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43156. if (pickingInfoA.distance < pickingInfoB.distance) {
  43157. return -1;
  43158. }
  43159. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43160. return 1;
  43161. }
  43162. else {
  43163. return 0;
  43164. }
  43165. };
  43166. /**
  43167. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43168. * @param sega the first point of the segment to test the intersection against
  43169. * @param segb the second point of the segment to test the intersection against
  43170. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43171. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43172. */
  43173. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43174. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43175. var u = segb.subtract(sega);
  43176. var v = rsegb.subtract(this.origin);
  43177. var w = sega.subtract(this.origin);
  43178. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43179. var b = BABYLON.Vector3.Dot(u, v);
  43180. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43181. var d = BABYLON.Vector3.Dot(u, w);
  43182. var e = BABYLON.Vector3.Dot(v, w);
  43183. var D = a * c - b * b; // always >= 0
  43184. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43185. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43186. // compute the line parameters of the two closest points
  43187. if (D < Ray.smallnum) {
  43188. sN = 0.0; // force using point P0 on segment S1
  43189. sD = 1.0; // to prevent possible division by 0.0 later
  43190. tN = e;
  43191. tD = c;
  43192. }
  43193. else {
  43194. sN = (b * e - c * d);
  43195. tN = (a * e - b * d);
  43196. if (sN < 0.0) {
  43197. sN = 0.0;
  43198. tN = e;
  43199. tD = c;
  43200. }
  43201. else if (sN > sD) {
  43202. sN = sD;
  43203. tN = e + b;
  43204. tD = c;
  43205. }
  43206. }
  43207. if (tN < 0.0) {
  43208. tN = 0.0;
  43209. // recompute sc for this edge
  43210. if (-d < 0.0) {
  43211. sN = 0.0;
  43212. }
  43213. else if (-d > a)
  43214. sN = sD;
  43215. else {
  43216. sN = -d;
  43217. sD = a;
  43218. }
  43219. }
  43220. else if (tN > tD) {
  43221. tN = tD;
  43222. // recompute sc for this edge
  43223. if ((-d + b) < 0.0) {
  43224. sN = 0;
  43225. }
  43226. else if ((-d + b) > a) {
  43227. sN = sD;
  43228. }
  43229. else {
  43230. sN = (-d + b);
  43231. sD = a;
  43232. }
  43233. }
  43234. // finally do the division to get sc and tc
  43235. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43236. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43237. // get the difference of the two closest points
  43238. var qtc = v.multiplyByFloats(tc, tc, tc);
  43239. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43240. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43241. if (isIntersected) {
  43242. return qtc.length();
  43243. }
  43244. return -1;
  43245. };
  43246. // Statics
  43247. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43248. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  43249. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  43250. var direction = end.subtract(start);
  43251. direction.normalize();
  43252. return new Ray(start, direction);
  43253. };
  43254. /**
  43255. * 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
  43256. * transformed to the given world matrix.
  43257. * @param origin The origin point
  43258. * @param end The end point
  43259. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43260. */
  43261. Ray.CreateNewFromTo = function (origin, end, world) {
  43262. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43263. var direction = end.subtract(origin);
  43264. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43265. direction.normalize();
  43266. return Ray.Transform(new Ray(origin, direction, length), world);
  43267. };
  43268. Ray.Transform = function (ray, matrix) {
  43269. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43270. Ray.TransformToRef(ray, matrix, result);
  43271. return result;
  43272. };
  43273. Ray.TransformToRef = function (ray, matrix, result) {
  43274. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43275. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43276. result.length = ray.length;
  43277. var dir = result.direction;
  43278. var len = dir.length();
  43279. if (!(len === 0 || len === 1)) {
  43280. var num = 1.0 / len;
  43281. dir.x *= num;
  43282. dir.y *= num;
  43283. dir.z *= num;
  43284. result.length *= len;
  43285. }
  43286. };
  43287. Ray.smallnum = 0.00000001;
  43288. Ray.rayl = 10e8;
  43289. return Ray;
  43290. }());
  43291. BABYLON.Ray = Ray;
  43292. })(BABYLON || (BABYLON = {}));
  43293. //# sourceMappingURL=babylon.ray.js.map
  43294. var BABYLON;
  43295. (function (BABYLON) {
  43296. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43297. if (boxMin.x > sphereCenter.x + sphereRadius)
  43298. return false;
  43299. if (sphereCenter.x - sphereRadius > boxMax.x)
  43300. return false;
  43301. if (boxMin.y > sphereCenter.y + sphereRadius)
  43302. return false;
  43303. if (sphereCenter.y - sphereRadius > boxMax.y)
  43304. return false;
  43305. if (boxMin.z > sphereCenter.z + sphereRadius)
  43306. return false;
  43307. if (sphereCenter.z - sphereRadius > boxMax.z)
  43308. return false;
  43309. return true;
  43310. };
  43311. var getLowestRoot = (function () {
  43312. var result = { root: 0, found: false };
  43313. return function (a, b, c, maxR) {
  43314. result.root = 0;
  43315. result.found = false;
  43316. var determinant = b * b - 4.0 * a * c;
  43317. if (determinant < 0)
  43318. return result;
  43319. var sqrtD = Math.sqrt(determinant);
  43320. var r1 = (-b - sqrtD) / (2.0 * a);
  43321. var r2 = (-b + sqrtD) / (2.0 * a);
  43322. if (r1 > r2) {
  43323. var temp = r2;
  43324. r2 = r1;
  43325. r1 = temp;
  43326. }
  43327. if (r1 > 0 && r1 < maxR) {
  43328. result.root = r1;
  43329. result.found = true;
  43330. return result;
  43331. }
  43332. if (r2 > 0 && r2 < maxR) {
  43333. result.root = r2;
  43334. result.found = true;
  43335. return result;
  43336. }
  43337. return result;
  43338. };
  43339. })();
  43340. var Collider = /** @class */ (function () {
  43341. function Collider() {
  43342. this.radius = BABYLON.Vector3.One();
  43343. this.retry = 0;
  43344. this.basePointWorld = BABYLON.Vector3.Zero();
  43345. this.velocityWorld = BABYLON.Vector3.Zero();
  43346. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43347. this._collisionPoint = BABYLON.Vector3.Zero();
  43348. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43349. this._tempVector = BABYLON.Vector3.Zero();
  43350. this._tempVector2 = BABYLON.Vector3.Zero();
  43351. this._tempVector3 = BABYLON.Vector3.Zero();
  43352. this._tempVector4 = BABYLON.Vector3.Zero();
  43353. this._edge = BABYLON.Vector3.Zero();
  43354. this._baseToVertex = BABYLON.Vector3.Zero();
  43355. this._destinationPoint = BABYLON.Vector3.Zero();
  43356. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43357. this._displacementVector = BABYLON.Vector3.Zero();
  43358. this._collisionMask = -1;
  43359. }
  43360. Object.defineProperty(Collider.prototype, "collisionMask", {
  43361. get: function () {
  43362. return this._collisionMask;
  43363. },
  43364. set: function (mask) {
  43365. this._collisionMask = !isNaN(mask) ? mask : -1;
  43366. },
  43367. enumerable: true,
  43368. configurable: true
  43369. });
  43370. // Methods
  43371. Collider.prototype._initialize = function (source, dir, e) {
  43372. this.velocity = dir;
  43373. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  43374. this.basePoint = source;
  43375. source.multiplyToRef(this.radius, this.basePointWorld);
  43376. dir.multiplyToRef(this.radius, this.velocityWorld);
  43377. this.velocityWorldLength = this.velocityWorld.length();
  43378. this.epsilon = e;
  43379. this.collisionFound = false;
  43380. };
  43381. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  43382. pa.subtractToRef(point, this._tempVector);
  43383. pb.subtractToRef(point, this._tempVector2);
  43384. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  43385. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43386. if (d < 0)
  43387. return false;
  43388. pc.subtractToRef(point, this._tempVector3);
  43389. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  43390. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43391. if (d < 0)
  43392. return false;
  43393. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  43394. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43395. return d >= 0;
  43396. };
  43397. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  43398. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  43399. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  43400. if (distance > this.velocityWorldLength + max + sphereRadius) {
  43401. return false;
  43402. }
  43403. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  43404. return false;
  43405. return true;
  43406. };
  43407. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  43408. var t0;
  43409. var embeddedInPlane = false;
  43410. //defensive programming, actually not needed.
  43411. if (!trianglePlaneArray) {
  43412. trianglePlaneArray = [];
  43413. }
  43414. if (!trianglePlaneArray[faceIndex]) {
  43415. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  43416. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  43417. }
  43418. var trianglePlane = trianglePlaneArray[faceIndex];
  43419. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  43420. return;
  43421. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  43422. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  43423. if (normalDotVelocity == 0) {
  43424. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  43425. return;
  43426. embeddedInPlane = true;
  43427. t0 = 0;
  43428. }
  43429. else {
  43430. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43431. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43432. if (t0 > t1) {
  43433. var temp = t1;
  43434. t1 = t0;
  43435. t0 = temp;
  43436. }
  43437. if (t0 > 1.0 || t1 < 0.0)
  43438. return;
  43439. if (t0 < 0)
  43440. t0 = 0;
  43441. if (t0 > 1.0)
  43442. t0 = 1.0;
  43443. }
  43444. this._collisionPoint.copyFromFloats(0, 0, 0);
  43445. var found = false;
  43446. var t = 1.0;
  43447. if (!embeddedInPlane) {
  43448. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  43449. this.velocity.scaleToRef(t0, this._tempVector);
  43450. this._planeIntersectionPoint.addInPlace(this._tempVector);
  43451. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  43452. found = true;
  43453. t = t0;
  43454. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  43455. }
  43456. }
  43457. if (!found) {
  43458. var velocitySquaredLength = this.velocity.lengthSquared();
  43459. var a = velocitySquaredLength;
  43460. this.basePoint.subtractToRef(p1, this._tempVector);
  43461. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43462. var c = this._tempVector.lengthSquared() - 1.0;
  43463. var lowestRoot = getLowestRoot(a, b, c, t);
  43464. if (lowestRoot.found) {
  43465. t = lowestRoot.root;
  43466. found = true;
  43467. this._collisionPoint.copyFrom(p1);
  43468. }
  43469. this.basePoint.subtractToRef(p2, this._tempVector);
  43470. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43471. c = this._tempVector.lengthSquared() - 1.0;
  43472. lowestRoot = getLowestRoot(a, b, c, t);
  43473. if (lowestRoot.found) {
  43474. t = lowestRoot.root;
  43475. found = true;
  43476. this._collisionPoint.copyFrom(p2);
  43477. }
  43478. this.basePoint.subtractToRef(p3, this._tempVector);
  43479. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43480. c = this._tempVector.lengthSquared() - 1.0;
  43481. lowestRoot = getLowestRoot(a, b, c, t);
  43482. if (lowestRoot.found) {
  43483. t = lowestRoot.root;
  43484. found = true;
  43485. this._collisionPoint.copyFrom(p3);
  43486. }
  43487. p2.subtractToRef(p1, this._edge);
  43488. p1.subtractToRef(this.basePoint, this._baseToVertex);
  43489. var edgeSquaredLength = this._edge.lengthSquared();
  43490. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43491. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43492. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43493. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43494. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43495. lowestRoot = getLowestRoot(a, b, c, t);
  43496. if (lowestRoot.found) {
  43497. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43498. if (f >= 0.0 && f <= 1.0) {
  43499. t = lowestRoot.root;
  43500. found = true;
  43501. this._edge.scaleInPlace(f);
  43502. p1.addToRef(this._edge, this._collisionPoint);
  43503. }
  43504. }
  43505. p3.subtractToRef(p2, this._edge);
  43506. p2.subtractToRef(this.basePoint, this._baseToVertex);
  43507. edgeSquaredLength = this._edge.lengthSquared();
  43508. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43509. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43510. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43511. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43512. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43513. lowestRoot = getLowestRoot(a, b, c, t);
  43514. if (lowestRoot.found) {
  43515. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43516. if (f >= 0.0 && f <= 1.0) {
  43517. t = lowestRoot.root;
  43518. found = true;
  43519. this._edge.scaleInPlace(f);
  43520. p2.addToRef(this._edge, this._collisionPoint);
  43521. }
  43522. }
  43523. p1.subtractToRef(p3, this._edge);
  43524. p3.subtractToRef(this.basePoint, this._baseToVertex);
  43525. edgeSquaredLength = this._edge.lengthSquared();
  43526. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43527. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43528. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43529. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43530. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43531. lowestRoot = getLowestRoot(a, b, c, t);
  43532. if (lowestRoot.found) {
  43533. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43534. if (f >= 0.0 && f <= 1.0) {
  43535. t = lowestRoot.root;
  43536. found = true;
  43537. this._edge.scaleInPlace(f);
  43538. p3.addToRef(this._edge, this._collisionPoint);
  43539. }
  43540. }
  43541. }
  43542. if (found) {
  43543. var distToCollision = t * this.velocity.length();
  43544. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  43545. if (!this.intersectionPoint) {
  43546. this.intersectionPoint = this._collisionPoint.clone();
  43547. }
  43548. else {
  43549. this.intersectionPoint.copyFrom(this._collisionPoint);
  43550. }
  43551. this.nearestDistance = distToCollision;
  43552. this.collisionFound = true;
  43553. }
  43554. }
  43555. };
  43556. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  43557. for (var i = indexStart; i < indexEnd; i += 3) {
  43558. var p1 = pts[indices[i] - decal];
  43559. var p2 = pts[indices[i + 1] - decal];
  43560. var p3 = pts[indices[i + 2] - decal];
  43561. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  43562. }
  43563. };
  43564. Collider.prototype._getResponse = function (pos, vel) {
  43565. pos.addToRef(vel, this._destinationPoint);
  43566. vel.scaleInPlace((this.nearestDistance / vel.length()));
  43567. this.basePoint.addToRef(vel, pos);
  43568. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  43569. this._slidePlaneNormal.normalize();
  43570. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  43571. pos.addInPlace(this._displacementVector);
  43572. this.intersectionPoint.addInPlace(this._displacementVector);
  43573. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  43574. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  43575. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  43576. };
  43577. return Collider;
  43578. }());
  43579. BABYLON.Collider = Collider;
  43580. })(BABYLON || (BABYLON = {}));
  43581. //# sourceMappingURL=babylon.collider.js.map
  43582. var BABYLON;
  43583. (function (BABYLON) {
  43584. //WebWorker code will be inserted to this variable.
  43585. BABYLON.CollisionWorker = "";
  43586. var WorkerTaskType;
  43587. (function (WorkerTaskType) {
  43588. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  43589. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  43590. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  43591. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  43592. var WorkerReplyType;
  43593. (function (WorkerReplyType) {
  43594. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  43595. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  43596. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  43597. var CollisionCoordinatorWorker = /** @class */ (function () {
  43598. function CollisionCoordinatorWorker() {
  43599. var _this = this;
  43600. this._scaledPosition = BABYLON.Vector3.Zero();
  43601. this._scaledVelocity = BABYLON.Vector3.Zero();
  43602. this.onMeshUpdated = function (mesh) {
  43603. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  43604. };
  43605. this.onGeometryUpdated = function (geometry) {
  43606. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  43607. };
  43608. this._afterRender = function () {
  43609. if (!_this._init)
  43610. return;
  43611. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  43612. return;
  43613. }
  43614. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  43615. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  43616. if (_this._runningUpdated > 4) {
  43617. return;
  43618. }
  43619. ++_this._runningUpdated;
  43620. var payload = {
  43621. updatedMeshes: _this._addUpdateMeshesList,
  43622. updatedGeometries: _this._addUpdateGeometriesList,
  43623. removedGeometries: _this._toRemoveGeometryArray,
  43624. removedMeshes: _this._toRemoveMeshesArray
  43625. };
  43626. var message = {
  43627. payload: payload,
  43628. taskType: WorkerTaskType.UPDATE
  43629. };
  43630. var serializable = [];
  43631. for (var id in payload.updatedGeometries) {
  43632. if (payload.updatedGeometries.hasOwnProperty(id)) {
  43633. //prepare transferables
  43634. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  43635. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  43636. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  43637. }
  43638. }
  43639. _this._worker.postMessage(message, serializable);
  43640. _this._addUpdateMeshesList = {};
  43641. _this._addUpdateGeometriesList = {};
  43642. _this._toRemoveGeometryArray = [];
  43643. _this._toRemoveMeshesArray = [];
  43644. };
  43645. this._onMessageFromWorker = function (e) {
  43646. var returnData = e.data;
  43647. if (returnData.error != WorkerReplyType.SUCCESS) {
  43648. //TODO what errors can be returned from the worker?
  43649. BABYLON.Tools.Warn("error returned from worker!");
  43650. return;
  43651. }
  43652. switch (returnData.taskType) {
  43653. case WorkerTaskType.INIT:
  43654. _this._init = true;
  43655. //Update the worked with ALL of the scene's current state
  43656. _this._scene.meshes.forEach(function (mesh) {
  43657. _this.onMeshAdded(mesh);
  43658. });
  43659. _this._scene.getGeometries().forEach(function (geometry) {
  43660. _this.onGeometryAdded(geometry);
  43661. });
  43662. break;
  43663. case WorkerTaskType.UPDATE:
  43664. _this._runningUpdated--;
  43665. break;
  43666. case WorkerTaskType.COLLIDE:
  43667. _this._runningCollisionTask = false;
  43668. var returnPayload = returnData.payload;
  43669. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  43670. return;
  43671. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  43672. if (callback) {
  43673. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  43674. if (mesh) {
  43675. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  43676. }
  43677. }
  43678. //cleanup
  43679. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  43680. break;
  43681. }
  43682. };
  43683. this._collisionsCallbackArray = [];
  43684. this._init = false;
  43685. this._runningUpdated = 0;
  43686. this._runningCollisionTask = false;
  43687. this._addUpdateMeshesList = {};
  43688. this._addUpdateGeometriesList = {};
  43689. this._toRemoveGeometryArray = [];
  43690. this._toRemoveMeshesArray = [];
  43691. }
  43692. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43693. if (!this._init)
  43694. return;
  43695. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  43696. return;
  43697. position.divideToRef(collider.radius, this._scaledPosition);
  43698. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43699. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  43700. var payload = {
  43701. collider: {
  43702. position: this._scaledPosition.asArray(),
  43703. velocity: this._scaledVelocity.asArray(),
  43704. radius: collider.radius.asArray()
  43705. },
  43706. collisionId: collisionIndex,
  43707. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  43708. maximumRetry: maximumRetry
  43709. };
  43710. var message = {
  43711. payload: payload,
  43712. taskType: WorkerTaskType.COLLIDE
  43713. };
  43714. this._worker.postMessage(message);
  43715. };
  43716. CollisionCoordinatorWorker.prototype.init = function (scene) {
  43717. this._scene = scene;
  43718. this._scene.registerAfterRender(this._afterRender);
  43719. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  43720. this._worker = new Worker(workerUrl);
  43721. this._worker.onmessage = this._onMessageFromWorker;
  43722. var message = {
  43723. payload: {},
  43724. taskType: WorkerTaskType.INIT
  43725. };
  43726. this._worker.postMessage(message);
  43727. };
  43728. CollisionCoordinatorWorker.prototype.destroy = function () {
  43729. this._scene.unregisterAfterRender(this._afterRender);
  43730. this._worker.terminate();
  43731. };
  43732. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  43733. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  43734. this.onMeshUpdated(mesh);
  43735. };
  43736. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  43737. this._toRemoveMeshesArray.push(mesh.uniqueId);
  43738. };
  43739. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  43740. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  43741. geometry.onGeometryUpdated = this.onGeometryUpdated;
  43742. this.onGeometryUpdated(geometry);
  43743. };
  43744. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  43745. this._toRemoveGeometryArray.push(geometry.id);
  43746. };
  43747. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  43748. var submeshes = [];
  43749. if (mesh.subMeshes) {
  43750. submeshes = mesh.subMeshes.map(function (sm, idx) {
  43751. var boundingInfo = sm.getBoundingInfo();
  43752. return {
  43753. position: idx,
  43754. verticesStart: sm.verticesStart,
  43755. verticesCount: sm.verticesCount,
  43756. indexStart: sm.indexStart,
  43757. indexCount: sm.indexCount,
  43758. hasMaterial: !!sm.getMaterial(),
  43759. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43760. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43761. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43762. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  43763. };
  43764. });
  43765. }
  43766. var geometryId = null;
  43767. if (mesh instanceof BABYLON.Mesh) {
  43768. var geometry = mesh.geometry;
  43769. geometryId = geometry ? geometry.id : null;
  43770. }
  43771. else if (mesh instanceof BABYLON.InstancedMesh) {
  43772. var geometry = mesh.sourceMesh.geometry;
  43773. geometryId = geometry ? geometry.id : null;
  43774. }
  43775. var boundingInfo = mesh.getBoundingInfo();
  43776. return {
  43777. uniqueId: mesh.uniqueId,
  43778. id: mesh.id,
  43779. name: mesh.name,
  43780. geometryId: geometryId,
  43781. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43782. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43783. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43784. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  43785. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  43786. subMeshes: submeshes,
  43787. checkCollisions: mesh.checkCollisions
  43788. };
  43789. };
  43790. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  43791. return {
  43792. id: geometry.id,
  43793. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  43794. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  43795. indices: new Uint32Array(geometry.getIndices() || []),
  43796. };
  43797. };
  43798. return CollisionCoordinatorWorker;
  43799. }());
  43800. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  43801. var CollisionCoordinatorLegacy = /** @class */ (function () {
  43802. function CollisionCoordinatorLegacy() {
  43803. this._scaledPosition = BABYLON.Vector3.Zero();
  43804. this._scaledVelocity = BABYLON.Vector3.Zero();
  43805. this._finalPosition = BABYLON.Vector3.Zero();
  43806. }
  43807. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43808. position.divideToRef(collider.radius, this._scaledPosition);
  43809. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43810. collider.collidedMesh = null;
  43811. collider.retry = 0;
  43812. collider.initialVelocity = this._scaledVelocity;
  43813. collider.initialPosition = this._scaledPosition;
  43814. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  43815. this._finalPosition.multiplyInPlace(collider.radius);
  43816. //run the callback
  43817. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  43818. };
  43819. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  43820. this._scene = scene;
  43821. };
  43822. CollisionCoordinatorLegacy.prototype.destroy = function () {
  43823. //Legacy need no destruction method.
  43824. };
  43825. //No update in legacy mode
  43826. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  43827. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  43828. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  43829. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  43830. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  43831. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  43832. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  43833. if (excludedMesh === void 0) { excludedMesh = null; }
  43834. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  43835. if (collider.retry >= maximumRetry) {
  43836. finalPosition.copyFrom(position);
  43837. return;
  43838. }
  43839. // Check if this is a mesh else camera or -1
  43840. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  43841. collider._initialize(position, velocity, closeDistance);
  43842. // Check all meshes
  43843. for (var index = 0; index < this._scene.meshes.length; index++) {
  43844. var mesh = this._scene.meshes[index];
  43845. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  43846. mesh._checkCollision(collider);
  43847. }
  43848. }
  43849. if (!collider.collisionFound) {
  43850. position.addToRef(velocity, finalPosition);
  43851. return;
  43852. }
  43853. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  43854. collider._getResponse(position, velocity);
  43855. }
  43856. if (velocity.length() <= closeDistance) {
  43857. finalPosition.copyFrom(position);
  43858. return;
  43859. }
  43860. collider.retry++;
  43861. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  43862. };
  43863. return CollisionCoordinatorLegacy;
  43864. }());
  43865. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  43866. })(BABYLON || (BABYLON = {}));
  43867. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  43868. var BABYLON;
  43869. (function (BABYLON) {
  43870. var Particle = /** @class */ (function () {
  43871. function Particle(particleSystem) {
  43872. this.particleSystem = particleSystem;
  43873. this.position = BABYLON.Vector3.Zero();
  43874. this.direction = BABYLON.Vector3.Zero();
  43875. this.color = new BABYLON.Color4(0, 0, 0, 0);
  43876. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  43877. this.lifeTime = 1.0;
  43878. this.age = 0;
  43879. this.size = 0;
  43880. this.angle = 0;
  43881. this.angularSpeed = 0;
  43882. this._currentFrameCounter = 0;
  43883. this.cellIndex = 0;
  43884. if (!this.particleSystem.isAnimationSheetEnabled) {
  43885. return;
  43886. }
  43887. this.cellIndex = this.particleSystem.startSpriteCellID;
  43888. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  43889. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  43890. }
  43891. else {
  43892. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  43893. }
  43894. }
  43895. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  43896. // (ageOffset / scaledUpdateSpeed) / available cells
  43897. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  43898. this._currentFrameCounter += scaledUpdateSpeed;
  43899. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  43900. this._currentFrameCounter = 0;
  43901. this.cellIndex++;
  43902. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43903. this.cellIndex = this.particleSystem.endSpriteCellID;
  43904. }
  43905. }
  43906. };
  43907. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  43908. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  43909. this.cellIndex++;
  43910. this._currentFrameCounter = 0;
  43911. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43912. if (this.particleSystem.spriteCellLoop) {
  43913. this.cellIndex = this.particleSystem.startSpriteCellID;
  43914. }
  43915. else {
  43916. this.cellIndex = this.particleSystem.endSpriteCellID;
  43917. }
  43918. }
  43919. }
  43920. else {
  43921. this._currentFrameCounter++;
  43922. }
  43923. };
  43924. Particle.prototype.copyTo = function (other) {
  43925. other.position.copyFrom(this.position);
  43926. other.direction.copyFrom(this.direction);
  43927. other.color.copyFrom(this.color);
  43928. other.colorStep.copyFrom(this.colorStep);
  43929. other.lifeTime = this.lifeTime;
  43930. other.age = this.age;
  43931. other.size = this.size;
  43932. other.angle = this.angle;
  43933. other.angularSpeed = this.angularSpeed;
  43934. other.particleSystem = this.particleSystem;
  43935. other.cellIndex = this.cellIndex;
  43936. };
  43937. return Particle;
  43938. }());
  43939. BABYLON.Particle = Particle;
  43940. })(BABYLON || (BABYLON = {}));
  43941. //# sourceMappingURL=babylon.particle.js.map
  43942. var BABYLON;
  43943. (function (BABYLON) {
  43944. var randomNumber = function (min, max) {
  43945. if (min === max) {
  43946. return (min);
  43947. }
  43948. var random = Math.random();
  43949. return ((random * (max - min)) + min);
  43950. };
  43951. var ParticleSystem = /** @class */ (function () {
  43952. // end of sheet animation
  43953. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  43954. if (customEffect === void 0) { customEffect = null; }
  43955. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  43956. if (epsilon === void 0) { epsilon = 0.01; }
  43957. var _this = this;
  43958. this.name = name;
  43959. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  43960. // Members
  43961. this.animations = [];
  43962. this.renderingGroupId = 0;
  43963. this.emitter = null;
  43964. this.emitRate = 10;
  43965. this.manualEmitCount = -1;
  43966. this.updateSpeed = 0.01;
  43967. this.targetStopDuration = 0;
  43968. this.disposeOnStop = false;
  43969. this.minEmitPower = 1;
  43970. this.maxEmitPower = 1;
  43971. this.minLifeTime = 1;
  43972. this.maxLifeTime = 1;
  43973. this.minSize = 1;
  43974. this.maxSize = 1;
  43975. this.minAngularSpeed = 0;
  43976. this.maxAngularSpeed = 0;
  43977. this.layerMask = 0x0FFFFFFF;
  43978. this.customShader = null;
  43979. this.preventAutoStart = false;
  43980. /**
  43981. * An event triggered when the system is disposed.
  43982. * @type {BABYLON.Observable}
  43983. */
  43984. this.onDisposeObservable = new BABYLON.Observable();
  43985. this.onAnimationEnd = null;
  43986. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  43987. this.forceDepthWrite = false;
  43988. this.gravity = BABYLON.Vector3.Zero();
  43989. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  43990. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  43991. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  43992. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43993. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43994. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43995. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  43996. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43997. this.particles = new Array();
  43998. this._stockParticles = new Array();
  43999. this._newPartsExcess = 0;
  44000. this._vertexBuffers = {};
  44001. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  44002. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  44003. this._scaledDirection = BABYLON.Vector3.Zero();
  44004. this._scaledGravity = BABYLON.Vector3.Zero();
  44005. this._currentRenderId = -1;
  44006. this._started = false;
  44007. this._stopped = false;
  44008. this._actualFrame = 0;
  44009. // sheet animation
  44010. this.startSpriteCellID = 0;
  44011. this.endSpriteCellID = 0;
  44012. this.spriteCellLoop = true;
  44013. this.spriteCellChangeSpeed = 0;
  44014. this.spriteCellWidth = 0;
  44015. this.spriteCellHeight = 0;
  44016. this._vertexBufferSize = 11;
  44017. this.appendParticleVertexes = null;
  44018. this.id = name;
  44019. this._capacity = capacity;
  44020. this._epsilon = epsilon;
  44021. if (_isAnimationSheetEnabled) {
  44022. this._vertexBufferSize = 12;
  44023. }
  44024. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44025. this._customEffect = customEffect;
  44026. scene.particleSystems.push(this);
  44027. this._createIndexBuffer();
  44028. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  44029. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  44030. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  44031. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  44032. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  44033. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  44034. if (this._isAnimationSheetEnabled) {
  44035. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  44036. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  44037. }
  44038. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44039. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44040. this._vertexBuffers["options"] = options;
  44041. // Default behaviors
  44042. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  44043. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  44044. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  44045. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  44046. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  44047. };
  44048. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  44049. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  44050. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  44051. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  44052. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  44053. };
  44054. this.updateFunction = function (particles) {
  44055. for (var index = 0; index < particles.length; index++) {
  44056. var particle = particles[index];
  44057. particle.age += _this._scaledUpdateSpeed;
  44058. if (particle.age >= particle.lifeTime) {
  44059. _this.recycleParticle(particle);
  44060. index--;
  44061. continue;
  44062. }
  44063. else {
  44064. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  44065. particle.color.addInPlace(_this._scaledColorStep);
  44066. if (particle.color.a < 0)
  44067. particle.color.a = 0;
  44068. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  44069. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  44070. particle.position.addInPlace(_this._scaledDirection);
  44071. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  44072. particle.direction.addInPlace(_this._scaledGravity);
  44073. if (_this._isAnimationSheetEnabled) {
  44074. particle.updateCellIndex(_this._scaledUpdateSpeed);
  44075. }
  44076. }
  44077. }
  44078. };
  44079. }
  44080. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  44081. set: function (callback) {
  44082. if (this._onDisposeObserver) {
  44083. this.onDisposeObservable.remove(this._onDisposeObserver);
  44084. }
  44085. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44086. },
  44087. enumerable: true,
  44088. configurable: true
  44089. });
  44090. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44091. get: function () {
  44092. return this._isAnimationSheetEnabled;
  44093. },
  44094. enumerable: true,
  44095. configurable: true
  44096. });
  44097. ParticleSystem.prototype._createIndexBuffer = function () {
  44098. var indices = [];
  44099. var index = 0;
  44100. for (var count = 0; count < this._capacity; count++) {
  44101. indices.push(index);
  44102. indices.push(index + 1);
  44103. indices.push(index + 2);
  44104. indices.push(index);
  44105. indices.push(index + 2);
  44106. indices.push(index + 3);
  44107. index += 4;
  44108. }
  44109. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44110. };
  44111. ParticleSystem.prototype.recycleParticle = function (particle) {
  44112. var lastParticle = this.particles.pop();
  44113. if (lastParticle !== particle) {
  44114. lastParticle.copyTo(particle);
  44115. this._stockParticles.push(lastParticle);
  44116. }
  44117. };
  44118. ParticleSystem.prototype.getCapacity = function () {
  44119. return this._capacity;
  44120. };
  44121. ParticleSystem.prototype.isAlive = function () {
  44122. return this._alive;
  44123. };
  44124. ParticleSystem.prototype.isStarted = function () {
  44125. return this._started;
  44126. };
  44127. ParticleSystem.prototype.start = function () {
  44128. this._started = true;
  44129. this._stopped = false;
  44130. this._actualFrame = 0;
  44131. };
  44132. ParticleSystem.prototype.stop = function () {
  44133. this._stopped = true;
  44134. };
  44135. // animation sheet
  44136. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44137. var offset = index * this._vertexBufferSize;
  44138. this._vertexData[offset] = particle.position.x;
  44139. this._vertexData[offset + 1] = particle.position.y;
  44140. this._vertexData[offset + 2] = particle.position.z;
  44141. this._vertexData[offset + 3] = particle.color.r;
  44142. this._vertexData[offset + 4] = particle.color.g;
  44143. this._vertexData[offset + 5] = particle.color.b;
  44144. this._vertexData[offset + 6] = particle.color.a;
  44145. this._vertexData[offset + 7] = particle.angle;
  44146. this._vertexData[offset + 8] = particle.size;
  44147. this._vertexData[offset + 9] = offsetX;
  44148. this._vertexData[offset + 10] = offsetY;
  44149. };
  44150. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  44151. if (offsetX === 0)
  44152. offsetX = this._epsilon;
  44153. else if (offsetX === 1)
  44154. offsetX = 1 - this._epsilon;
  44155. if (offsetY === 0)
  44156. offsetY = this._epsilon;
  44157. else if (offsetY === 1)
  44158. offsetY = 1 - this._epsilon;
  44159. var offset = index * this._vertexBufferSize;
  44160. this._vertexData[offset] = particle.position.x;
  44161. this._vertexData[offset + 1] = particle.position.y;
  44162. this._vertexData[offset + 2] = particle.position.z;
  44163. this._vertexData[offset + 3] = particle.color.r;
  44164. this._vertexData[offset + 4] = particle.color.g;
  44165. this._vertexData[offset + 5] = particle.color.b;
  44166. this._vertexData[offset + 6] = particle.color.a;
  44167. this._vertexData[offset + 7] = particle.angle;
  44168. this._vertexData[offset + 8] = particle.size;
  44169. this._vertexData[offset + 9] = offsetX;
  44170. this._vertexData[offset + 10] = offsetY;
  44171. this._vertexData[offset + 11] = particle.cellIndex;
  44172. };
  44173. ParticleSystem.prototype._update = function (newParticles) {
  44174. // Update current
  44175. this._alive = this.particles.length > 0;
  44176. this.updateFunction(this.particles);
  44177. // Add new ones
  44178. var worldMatrix;
  44179. if (this.emitter.position) {
  44180. var emitterMesh = this.emitter;
  44181. worldMatrix = emitterMesh.getWorldMatrix();
  44182. }
  44183. else {
  44184. var emitterPosition = this.emitter;
  44185. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44186. }
  44187. var particle;
  44188. for (var index = 0; index < newParticles; index++) {
  44189. if (this.particles.length === this._capacity) {
  44190. break;
  44191. }
  44192. if (this._stockParticles.length !== 0) {
  44193. particle = this._stockParticles.pop();
  44194. particle.age = 0;
  44195. particle.cellIndex = this.startSpriteCellID;
  44196. }
  44197. else {
  44198. particle = new BABYLON.Particle(this);
  44199. }
  44200. this.particles.push(particle);
  44201. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44202. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44203. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44204. particle.size = randomNumber(this.minSize, this.maxSize);
  44205. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44206. this.startPositionFunction(worldMatrix, particle.position, particle);
  44207. var step = randomNumber(0, 1.0);
  44208. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44209. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44210. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44211. }
  44212. };
  44213. ParticleSystem.prototype._getEffect = function () {
  44214. if (this._customEffect) {
  44215. return this._customEffect;
  44216. }
  44217. ;
  44218. var defines = [];
  44219. if (this._scene.clipPlane) {
  44220. defines.push("#define CLIPPLANE");
  44221. }
  44222. if (this._isAnimationSheetEnabled) {
  44223. defines.push("#define ANIMATESHEET");
  44224. }
  44225. // Effect
  44226. var join = defines.join("\n");
  44227. if (this._cachedDefines !== join) {
  44228. this._cachedDefines = join;
  44229. var attributesNamesOrOptions;
  44230. var effectCreationOption;
  44231. if (this._isAnimationSheetEnabled) {
  44232. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44233. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44234. }
  44235. else {
  44236. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44237. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44238. }
  44239. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44240. }
  44241. return this._effect;
  44242. };
  44243. ParticleSystem.prototype.animate = function () {
  44244. if (!this._started)
  44245. return;
  44246. var effect = this._getEffect();
  44247. // Check
  44248. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44249. return;
  44250. if (this._currentRenderId === this._scene.getRenderId()) {
  44251. return;
  44252. }
  44253. this._currentRenderId = this._scene.getRenderId();
  44254. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44255. // determine the number of particles we need to create
  44256. var newParticles;
  44257. if (this.manualEmitCount > -1) {
  44258. newParticles = this.manualEmitCount;
  44259. this._newPartsExcess = 0;
  44260. this.manualEmitCount = 0;
  44261. }
  44262. else {
  44263. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44264. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44265. }
  44266. if (this._newPartsExcess > 1.0) {
  44267. newParticles += this._newPartsExcess >> 0;
  44268. this._newPartsExcess -= this._newPartsExcess >> 0;
  44269. }
  44270. this._alive = false;
  44271. if (!this._stopped) {
  44272. this._actualFrame += this._scaledUpdateSpeed;
  44273. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44274. this.stop();
  44275. }
  44276. else {
  44277. newParticles = 0;
  44278. }
  44279. this._update(newParticles);
  44280. // Stopped?
  44281. if (this._stopped) {
  44282. if (!this._alive) {
  44283. this._started = false;
  44284. if (this.onAnimationEnd) {
  44285. this.onAnimationEnd();
  44286. }
  44287. if (this.disposeOnStop) {
  44288. this._scene._toBeDisposed.push(this);
  44289. }
  44290. }
  44291. }
  44292. // Animation sheet
  44293. if (this._isAnimationSheetEnabled) {
  44294. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44295. }
  44296. else {
  44297. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44298. }
  44299. // Update VBO
  44300. var offset = 0;
  44301. for (var index = 0; index < this.particles.length; index++) {
  44302. var particle = this.particles[index];
  44303. this.appendParticleVertexes(offset, particle);
  44304. offset += 4;
  44305. }
  44306. if (this._vertexBuffer) {
  44307. this._vertexBuffer.update(this._vertexData);
  44308. }
  44309. };
  44310. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44311. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44312. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44313. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44314. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44315. };
  44316. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  44317. this._appendParticleVertex(offset++, particle, 0, 0);
  44318. this._appendParticleVertex(offset++, particle, 1, 0);
  44319. this._appendParticleVertex(offset++, particle, 1, 1);
  44320. this._appendParticleVertex(offset++, particle, 0, 1);
  44321. };
  44322. ParticleSystem.prototype.rebuild = function () {
  44323. this._createIndexBuffer();
  44324. if (this._vertexBuffer) {
  44325. this._vertexBuffer._rebuild();
  44326. }
  44327. };
  44328. ParticleSystem.prototype.render = function () {
  44329. var effect = this._getEffect();
  44330. // Check
  44331. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44332. return 0;
  44333. var engine = this._scene.getEngine();
  44334. // Render
  44335. engine.enableEffect(effect);
  44336. engine.setState(false);
  44337. var viewMatrix = this._scene.getViewMatrix();
  44338. effect.setTexture("diffuseSampler", this.particleTexture);
  44339. effect.setMatrix("view", viewMatrix);
  44340. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44341. if (this._isAnimationSheetEnabled) {
  44342. var baseSize = this.particleTexture.getBaseSize();
  44343. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44344. }
  44345. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44346. if (this._scene.clipPlane) {
  44347. var clipPlane = this._scene.clipPlane;
  44348. var invView = viewMatrix.clone();
  44349. invView.invert();
  44350. effect.setMatrix("invView", invView);
  44351. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44352. }
  44353. // VBOs
  44354. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44355. // Draw order
  44356. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44357. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44358. }
  44359. else {
  44360. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44361. }
  44362. if (this.forceDepthWrite) {
  44363. engine.setDepthWrite(true);
  44364. }
  44365. engine.draw(true, 0, this.particles.length * 6);
  44366. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44367. return this.particles.length;
  44368. };
  44369. ParticleSystem.prototype.dispose = function () {
  44370. if (this._vertexBuffer) {
  44371. this._vertexBuffer.dispose();
  44372. this._vertexBuffer = null;
  44373. }
  44374. if (this._indexBuffer) {
  44375. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44376. this._indexBuffer = null;
  44377. }
  44378. if (this.particleTexture) {
  44379. this.particleTexture.dispose();
  44380. this.particleTexture = null;
  44381. }
  44382. // Remove from scene
  44383. var index = this._scene.particleSystems.indexOf(this);
  44384. if (index > -1) {
  44385. this._scene.particleSystems.splice(index, 1);
  44386. }
  44387. // Callback
  44388. this.onDisposeObservable.notifyObservers(this);
  44389. this.onDisposeObservable.clear();
  44390. };
  44391. // Clone
  44392. ParticleSystem.prototype.clone = function (name, newEmitter) {
  44393. var custom = null;
  44394. var program = null;
  44395. if (this.customShader != null) {
  44396. program = this.customShader;
  44397. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44398. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44399. }
  44400. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  44401. result.customShader = program;
  44402. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  44403. if (newEmitter === undefined) {
  44404. newEmitter = this.emitter;
  44405. }
  44406. result.emitter = newEmitter;
  44407. if (this.particleTexture) {
  44408. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  44409. }
  44410. if (!this.preventAutoStart) {
  44411. result.start();
  44412. }
  44413. return result;
  44414. };
  44415. ParticleSystem.prototype.serialize = function () {
  44416. var serializationObject = {};
  44417. serializationObject.name = this.name;
  44418. serializationObject.id = this.id;
  44419. // Emitter
  44420. if (this.emitter.position) {
  44421. var emitterMesh = this.emitter;
  44422. serializationObject.emitterId = emitterMesh.id;
  44423. }
  44424. else {
  44425. var emitterPosition = this.emitter;
  44426. serializationObject.emitter = emitterPosition.asArray();
  44427. }
  44428. serializationObject.capacity = this.getCapacity();
  44429. if (this.particleTexture) {
  44430. serializationObject.textureName = this.particleTexture.name;
  44431. }
  44432. // Animations
  44433. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  44434. // Particle system
  44435. serializationObject.minAngularSpeed = this.minAngularSpeed;
  44436. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  44437. serializationObject.minSize = this.minSize;
  44438. serializationObject.maxSize = this.maxSize;
  44439. serializationObject.minEmitPower = this.minEmitPower;
  44440. serializationObject.maxEmitPower = this.maxEmitPower;
  44441. serializationObject.minLifeTime = this.minLifeTime;
  44442. serializationObject.maxLifeTime = this.maxLifeTime;
  44443. serializationObject.emitRate = this.emitRate;
  44444. serializationObject.minEmitBox = this.minEmitBox.asArray();
  44445. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  44446. serializationObject.gravity = this.gravity.asArray();
  44447. serializationObject.direction1 = this.direction1.asArray();
  44448. serializationObject.direction2 = this.direction2.asArray();
  44449. serializationObject.color1 = this.color1.asArray();
  44450. serializationObject.color2 = this.color2.asArray();
  44451. serializationObject.colorDead = this.colorDead.asArray();
  44452. serializationObject.updateSpeed = this.updateSpeed;
  44453. serializationObject.targetStopDuration = this.targetStopDuration;
  44454. serializationObject.textureMask = this.textureMask.asArray();
  44455. serializationObject.blendMode = this.blendMode;
  44456. serializationObject.customShader = this.customShader;
  44457. serializationObject.preventAutoStart = this.preventAutoStart;
  44458. return serializationObject;
  44459. };
  44460. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  44461. var name = parsedParticleSystem.name;
  44462. var custom = null;
  44463. var program = null;
  44464. if (parsedParticleSystem.customShader) {
  44465. program = parsedParticleSystem.customShader;
  44466. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44467. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44468. }
  44469. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  44470. particleSystem.customShader = program;
  44471. if (parsedParticleSystem.id) {
  44472. particleSystem.id = parsedParticleSystem.id;
  44473. }
  44474. // Auto start
  44475. if (parsedParticleSystem.preventAutoStart) {
  44476. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  44477. }
  44478. // Texture
  44479. if (parsedParticleSystem.textureName) {
  44480. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  44481. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  44482. }
  44483. // Emitter
  44484. if (parsedParticleSystem.emitterId) {
  44485. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  44486. }
  44487. else {
  44488. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  44489. }
  44490. // Animations
  44491. if (parsedParticleSystem.animations) {
  44492. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  44493. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  44494. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44495. }
  44496. }
  44497. if (parsedParticleSystem.autoAnimate) {
  44498. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  44499. }
  44500. // Particle system
  44501. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  44502. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  44503. particleSystem.minSize = parsedParticleSystem.minSize;
  44504. particleSystem.maxSize = parsedParticleSystem.maxSize;
  44505. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  44506. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  44507. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  44508. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  44509. particleSystem.emitRate = parsedParticleSystem.emitRate;
  44510. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  44511. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  44512. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  44513. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  44514. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  44515. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  44516. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  44517. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  44518. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  44519. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  44520. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  44521. particleSystem.blendMode = parsedParticleSystem.blendMode;
  44522. if (!particleSystem.preventAutoStart) {
  44523. particleSystem.start();
  44524. }
  44525. return particleSystem;
  44526. };
  44527. // Statics
  44528. ParticleSystem.BLENDMODE_ONEONE = 0;
  44529. ParticleSystem.BLENDMODE_STANDARD = 1;
  44530. return ParticleSystem;
  44531. }());
  44532. BABYLON.ParticleSystem = ParticleSystem;
  44533. })(BABYLON || (BABYLON = {}));
  44534. //# sourceMappingURL=babylon.particleSystem.js.map
  44535. var BABYLON;
  44536. (function (BABYLON) {
  44537. var SolidParticle = /** @class */ (function () {
  44538. /**
  44539. * Creates a Solid Particle object.
  44540. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  44541. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  44542. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  44543. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  44544. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  44545. * `shapeId` (integer) is the model shape identifier in the SPS.
  44546. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  44547. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  44548. */
  44549. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  44550. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  44551. this.idx = 0; // particle global index
  44552. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  44553. this.position = BABYLON.Vector3.Zero(); // position
  44554. this.rotation = BABYLON.Vector3.Zero(); // rotation
  44555. this.scaling = BABYLON.Vector3.One(); // scaling
  44556. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  44557. this.velocity = BABYLON.Vector3.Zero(); // velocity
  44558. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  44559. this.alive = true; // alive
  44560. this.isVisible = true; // visibility
  44561. this._pos = 0; // index of this particle in the global "positions" array
  44562. this._ind = 0; // index of this particle in the global "indices" array
  44563. this.shapeId = 0; // model shape id
  44564. this.idxInShape = 0; // index of the particle in its shape id
  44565. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  44566. this.idx = particleIndex;
  44567. this._pos = positionIndex;
  44568. this._ind = indiceIndex;
  44569. this._model = model;
  44570. this.shapeId = shapeId;
  44571. this.idxInShape = idxInShape;
  44572. this._sps = sps;
  44573. if (modelBoundingInfo) {
  44574. this._modelBoundingInfo = modelBoundingInfo;
  44575. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  44576. }
  44577. }
  44578. Object.defineProperty(SolidParticle.prototype, "scale", {
  44579. /**
  44580. * legacy support, changed scale to scaling
  44581. */
  44582. get: function () {
  44583. return this.scaling;
  44584. },
  44585. set: function (scale) {
  44586. this.scaling = scale;
  44587. },
  44588. enumerable: true,
  44589. configurable: true
  44590. });
  44591. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  44592. /**
  44593. * legacy support, changed quaternion to rotationQuaternion
  44594. */
  44595. get: function () {
  44596. return this.rotationQuaternion;
  44597. },
  44598. set: function (q) {
  44599. this.rotationQuaternion = q;
  44600. },
  44601. enumerable: true,
  44602. configurable: true
  44603. });
  44604. /**
  44605. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  44606. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  44607. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  44608. */
  44609. SolidParticle.prototype.intersectsMesh = function (target) {
  44610. if (!this._boundingInfo || !target._boundingInfo) {
  44611. return false;
  44612. }
  44613. if (this._sps._bSphereOnly) {
  44614. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  44615. }
  44616. return this._boundingInfo.intersects(target._boundingInfo, false);
  44617. };
  44618. return SolidParticle;
  44619. }());
  44620. BABYLON.SolidParticle = SolidParticle;
  44621. var ModelShape = /** @class */ (function () {
  44622. /**
  44623. * 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.
  44624. * SPS internal tool, don't use it manually.
  44625. */
  44626. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  44627. this._indicesLength = 0; // length of the shape in the model indices array
  44628. this.shapeID = id;
  44629. this._shape = shape;
  44630. this._indicesLength = indicesLength;
  44631. this._shapeUV = shapeUV;
  44632. this._positionFunction = posFunction;
  44633. this._vertexFunction = vtxFunction;
  44634. }
  44635. return ModelShape;
  44636. }());
  44637. BABYLON.ModelShape = ModelShape;
  44638. var DepthSortedParticle = /** @class */ (function () {
  44639. function DepthSortedParticle() {
  44640. this.ind = 0; // index of the particle in the "indices" array
  44641. this.indicesLength = 0; // length of the particle shape in the "indices" array
  44642. this.sqDistance = 0.0; // squared distance from the particle to the camera
  44643. }
  44644. return DepthSortedParticle;
  44645. }());
  44646. BABYLON.DepthSortedParticle = DepthSortedParticle;
  44647. })(BABYLON || (BABYLON = {}));
  44648. //# sourceMappingURL=babylon.solidParticle.js.map
  44649. var BABYLON;
  44650. (function (BABYLON) {
  44651. /**
  44652. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  44653. */
  44654. var SolidParticleSystem = /** @class */ (function () {
  44655. /**
  44656. * Creates a SPS (Solid Particle System) object.
  44657. * `name` (String) is the SPS name, this will be the underlying mesh name.
  44658. * `scene` (Scene) is the scene in which the SPS is added.
  44659. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  44660. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  44661. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  44662. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  44663. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  44664. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  44665. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  44666. */
  44667. function SolidParticleSystem(name, scene, options) {
  44668. // public members
  44669. /**
  44670. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  44671. * Example : var p = SPS.particles[i];
  44672. */
  44673. this.particles = new Array();
  44674. /**
  44675. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  44676. */
  44677. this.nbParticles = 0;
  44678. /**
  44679. * If the particles must ever face the camera (default false). Useful for planar particles.
  44680. */
  44681. this.billboard = false;
  44682. /**
  44683. * Recompute normals when adding a shape
  44684. */
  44685. this.recomputeNormals = true;
  44686. /**
  44687. * This a counter ofr your own usage. It's not set by any SPS functions.
  44688. */
  44689. this.counter = 0;
  44690. /**
  44691. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  44692. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  44693. */
  44694. this.vars = {};
  44695. this._positions = new Array();
  44696. this._indices = new Array();
  44697. this._normals = new Array();
  44698. this._colors = new Array();
  44699. this._uvs = new Array();
  44700. this._index = 0; // indices index
  44701. this._updatable = true;
  44702. this._pickable = false;
  44703. this._isVisibilityBoxLocked = false;
  44704. this._alwaysVisible = false;
  44705. this._depthSort = false;
  44706. this._shapeCounter = 0;
  44707. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  44708. this._color = new BABYLON.Color4(0, 0, 0, 0);
  44709. this._computeParticleColor = true;
  44710. this._computeParticleTexture = true;
  44711. this._computeParticleRotation = true;
  44712. this._computeParticleVertex = false;
  44713. this._computeBoundingBox = false;
  44714. this._depthSortParticles = true;
  44715. this._cam_axisZ = BABYLON.Vector3.Zero();
  44716. this._cam_axisY = BABYLON.Vector3.Zero();
  44717. this._cam_axisX = BABYLON.Vector3.Zero();
  44718. this._axisZ = BABYLON.Axis.Z;
  44719. this._camDir = BABYLON.Vector3.Zero();
  44720. this._camInvertedPosition = BABYLON.Vector3.Zero();
  44721. this._rotMatrix = new BABYLON.Matrix();
  44722. this._invertMatrix = new BABYLON.Matrix();
  44723. this._rotated = BABYLON.Vector3.Zero();
  44724. this._quaternion = new BABYLON.Quaternion();
  44725. this._vertex = BABYLON.Vector3.Zero();
  44726. this._normal = BABYLON.Vector3.Zero();
  44727. this._yaw = 0.0;
  44728. this._pitch = 0.0;
  44729. this._roll = 0.0;
  44730. this._halfroll = 0.0;
  44731. this._halfpitch = 0.0;
  44732. this._halfyaw = 0.0;
  44733. this._sinRoll = 0.0;
  44734. this._cosRoll = 0.0;
  44735. this._sinPitch = 0.0;
  44736. this._cosPitch = 0.0;
  44737. this._sinYaw = 0.0;
  44738. this._cosYaw = 0.0;
  44739. this._mustUnrotateFixedNormals = false;
  44740. this._minimum = BABYLON.Tmp.Vector3[0];
  44741. this._maximum = BABYLON.Tmp.Vector3[1];
  44742. this._minBbox = BABYLON.Tmp.Vector3[4];
  44743. this._maxBbox = BABYLON.Tmp.Vector3[5];
  44744. this._particlesIntersect = false;
  44745. this._depthSortFunction = function (p1, p2) {
  44746. return (p2.sqDistance - p1.sqDistance);
  44747. };
  44748. this._needs32Bits = false;
  44749. this._bSphereOnly = false;
  44750. this._bSphereRadiusFactor = 1.0;
  44751. this.name = name;
  44752. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44753. this._camera = scene.activeCamera;
  44754. this._pickable = options ? options.isPickable : false;
  44755. this._depthSort = options ? options.enableDepthSort : false;
  44756. this._particlesIntersect = options ? options.particleIntersection : false;
  44757. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  44758. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  44759. if (options && options.updatable) {
  44760. this._updatable = options.updatable;
  44761. }
  44762. else {
  44763. this._updatable = true;
  44764. }
  44765. if (this._pickable) {
  44766. this.pickedParticles = [];
  44767. }
  44768. if (this._depthSort) {
  44769. this.depthSortedParticles = [];
  44770. }
  44771. }
  44772. /**
  44773. * Builds the SPS underlying mesh. Returns a standard Mesh.
  44774. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  44775. */
  44776. SolidParticleSystem.prototype.buildMesh = function () {
  44777. if (this.nbParticles === 0) {
  44778. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  44779. this.addShape(triangle, 1);
  44780. triangle.dispose();
  44781. }
  44782. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  44783. this._positions32 = new Float32Array(this._positions);
  44784. this._uvs32 = new Float32Array(this._uvs);
  44785. this._colors32 = new Float32Array(this._colors);
  44786. if (this.recomputeNormals) {
  44787. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  44788. }
  44789. this._normals32 = new Float32Array(this._normals);
  44790. this._fixedNormal32 = new Float32Array(this._normals);
  44791. if (this._mustUnrotateFixedNormals) {
  44792. this._unrotateFixedNormals();
  44793. }
  44794. var vertexData = new BABYLON.VertexData();
  44795. vertexData.indices = this._indices32;
  44796. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  44797. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  44798. if (this._uvs32) {
  44799. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  44800. ;
  44801. }
  44802. if (this._colors32) {
  44803. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  44804. }
  44805. var mesh = new BABYLON.Mesh(this.name, this._scene);
  44806. vertexData.applyToMesh(mesh, this._updatable);
  44807. this.mesh = mesh;
  44808. this.mesh.isPickable = this._pickable;
  44809. // free memory
  44810. if (!this._depthSort) {
  44811. this._indices = null;
  44812. }
  44813. this._positions = null;
  44814. this._normals = null;
  44815. this._uvs = null;
  44816. this._colors = null;
  44817. if (!this._updatable) {
  44818. this.particles.length = 0;
  44819. }
  44820. return mesh;
  44821. };
  44822. /**
  44823. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  44824. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  44825. * Thus the particles generated from `digest()` have their property `position` set yet.
  44826. * `mesh` ( Mesh ) is the mesh to be digested
  44827. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  44828. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  44829. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  44830. */
  44831. SolidParticleSystem.prototype.digest = function (mesh, options) {
  44832. var size = (options && options.facetNb) || 1;
  44833. var number = (options && options.number) || 0;
  44834. var delta = (options && options.delta) || 0;
  44835. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44836. var meshInd = mesh.getIndices();
  44837. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44838. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44839. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44840. var f = 0; // facet counter
  44841. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  44842. // compute size from number
  44843. if (number) {
  44844. number = (number > totalFacets) ? totalFacets : number;
  44845. size = Math.round(totalFacets / number);
  44846. delta = 0;
  44847. }
  44848. else {
  44849. size = (size > totalFacets) ? totalFacets : size;
  44850. }
  44851. var facetPos = []; // submesh positions
  44852. var facetInd = []; // submesh indices
  44853. var facetUV = []; // submesh UV
  44854. var facetCol = []; // submesh colors
  44855. var barycenter = BABYLON.Tmp.Vector3[0];
  44856. var sizeO = size;
  44857. while (f < totalFacets) {
  44858. size = sizeO + Math.floor((1 + delta) * Math.random());
  44859. if (f > totalFacets - size) {
  44860. size = totalFacets - f;
  44861. }
  44862. // reset temp arrays
  44863. facetPos.length = 0;
  44864. facetInd.length = 0;
  44865. facetUV.length = 0;
  44866. facetCol.length = 0;
  44867. // iterate over "size" facets
  44868. var fi = 0;
  44869. for (var j = f * 3; j < (f + size) * 3; j++) {
  44870. facetInd.push(fi);
  44871. var i = meshInd[j];
  44872. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  44873. if (meshUV) {
  44874. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  44875. }
  44876. if (meshCol) {
  44877. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  44878. }
  44879. fi++;
  44880. }
  44881. // create a model shape for each single particle
  44882. var idx = this.nbParticles;
  44883. var shape = this._posToShape(facetPos);
  44884. var shapeUV = this._uvsToShapeUV(facetUV);
  44885. // compute the barycenter of the shape
  44886. var v;
  44887. for (v = 0; v < shape.length; v++) {
  44888. barycenter.addInPlace(shape[v]);
  44889. }
  44890. barycenter.scaleInPlace(1 / shape.length);
  44891. // shift the shape from its barycenter to the origin
  44892. for (v = 0; v < shape.length; v++) {
  44893. shape[v].subtractInPlace(barycenter);
  44894. }
  44895. var bInfo;
  44896. if (this._particlesIntersect) {
  44897. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  44898. }
  44899. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  44900. // add the particle in the SPS
  44901. var currentPos = this._positions.length;
  44902. var currentInd = this._indices.length;
  44903. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  44904. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  44905. // initialize the particle position
  44906. this.particles[this.nbParticles].position.addInPlace(barycenter);
  44907. this._index += shape.length;
  44908. idx++;
  44909. this.nbParticles++;
  44910. this._shapeCounter++;
  44911. f += size;
  44912. }
  44913. return this;
  44914. };
  44915. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  44916. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  44917. var index = 0;
  44918. var idx = 0;
  44919. for (var p = 0; p < this.particles.length; p++) {
  44920. this._particle = this.particles[p];
  44921. this._shape = this._particle._model._shape;
  44922. if (this._particle.rotationQuaternion) {
  44923. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  44924. }
  44925. else {
  44926. this._yaw = this._particle.rotation.y;
  44927. this._pitch = this._particle.rotation.x;
  44928. this._roll = this._particle.rotation.z;
  44929. this._quaternionRotationYPR();
  44930. }
  44931. this._quaternionToRotationMatrix();
  44932. this._rotMatrix.invertToRef(this._invertMatrix);
  44933. for (var pt = 0; pt < this._shape.length; pt++) {
  44934. idx = index + pt * 3;
  44935. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  44936. this._fixedNormal32[idx] = this._normal.x;
  44937. this._fixedNormal32[idx + 1] = this._normal.y;
  44938. this._fixedNormal32[idx + 2] = this._normal.z;
  44939. }
  44940. index = idx + 3;
  44941. }
  44942. };
  44943. //reset copy
  44944. SolidParticleSystem.prototype._resetCopy = function () {
  44945. this._copy.position.x = 0;
  44946. this._copy.position.y = 0;
  44947. this._copy.position.z = 0;
  44948. this._copy.rotation.x = 0;
  44949. this._copy.rotation.y = 0;
  44950. this._copy.rotation.z = 0;
  44951. this._copy.rotationQuaternion = null;
  44952. this._copy.scaling.x = 1.0;
  44953. this._copy.scaling.y = 1.0;
  44954. this._copy.scaling.z = 1.0;
  44955. this._copy.uvs.x = 0;
  44956. this._copy.uvs.y = 0;
  44957. this._copy.uvs.z = 1.0;
  44958. this._copy.uvs.w = 1.0;
  44959. this._copy.color = null;
  44960. };
  44961. // _meshBuilder : inserts the shape model in the global SPS mesh
  44962. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  44963. var i;
  44964. var u = 0;
  44965. var c = 0;
  44966. var n = 0;
  44967. this._resetCopy();
  44968. if (options && options.positionFunction) {
  44969. options.positionFunction(this._copy, idx, idxInShape);
  44970. this._mustUnrotateFixedNormals = true;
  44971. }
  44972. if (this._copy.rotationQuaternion) {
  44973. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44974. }
  44975. else {
  44976. this._yaw = this._copy.rotation.y;
  44977. this._pitch = this._copy.rotation.x;
  44978. this._roll = this._copy.rotation.z;
  44979. this._quaternionRotationYPR();
  44980. }
  44981. this._quaternionToRotationMatrix();
  44982. for (i = 0; i < shape.length; i++) {
  44983. this._vertex.x = shape[i].x;
  44984. this._vertex.y = shape[i].y;
  44985. this._vertex.z = shape[i].z;
  44986. if (options && options.vertexFunction) {
  44987. options.vertexFunction(this._copy, this._vertex, i);
  44988. }
  44989. this._vertex.x *= this._copy.scaling.x;
  44990. this._vertex.y *= this._copy.scaling.y;
  44991. this._vertex.z *= this._copy.scaling.z;
  44992. this._vertex.x += this._copy.pivot.x;
  44993. this._vertex.y += this._copy.pivot.y;
  44994. this._vertex.z += this._copy.pivot.z;
  44995. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  44996. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  44997. if (meshUV) {
  44998. 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);
  44999. u += 2;
  45000. }
  45001. if (this._copy.color) {
  45002. this._color = this._copy.color;
  45003. }
  45004. else if (meshCol && meshCol[c] !== undefined) {
  45005. this._color.r = meshCol[c];
  45006. this._color.g = meshCol[c + 1];
  45007. this._color.b = meshCol[c + 2];
  45008. this._color.a = meshCol[c + 3];
  45009. }
  45010. else {
  45011. this._color.r = 1.0;
  45012. this._color.g = 1.0;
  45013. this._color.b = 1.0;
  45014. this._color.a = 1.0;
  45015. }
  45016. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  45017. c += 4;
  45018. if (!this.recomputeNormals && meshNor) {
  45019. this._normal.x = meshNor[n];
  45020. this._normal.y = meshNor[n + 1];
  45021. this._normal.z = meshNor[n + 2];
  45022. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  45023. normals.push(this._normal.x, this._normal.y, this._normal.z);
  45024. n += 3;
  45025. }
  45026. }
  45027. for (i = 0; i < meshInd.length; i++) {
  45028. var current_ind = p + meshInd[i];
  45029. indices.push(current_ind);
  45030. if (current_ind > 65535) {
  45031. this._needs32Bits = true;
  45032. }
  45033. }
  45034. if (this._pickable) {
  45035. var nbfaces = meshInd.length / 3;
  45036. for (i = 0; i < nbfaces; i++) {
  45037. this.pickedParticles.push({ idx: idx, faceId: i });
  45038. }
  45039. }
  45040. if (this._depthSort) {
  45041. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  45042. }
  45043. return this._copy;
  45044. };
  45045. // returns a shape array from positions array
  45046. SolidParticleSystem.prototype._posToShape = function (positions) {
  45047. var shape = [];
  45048. for (var i = 0; i < positions.length; i += 3) {
  45049. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  45050. }
  45051. return shape;
  45052. };
  45053. // returns a shapeUV array from a Vector4 uvs
  45054. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  45055. var shapeUV = [];
  45056. if (uvs) {
  45057. for (var i = 0; i < uvs.length; i++)
  45058. shapeUV.push(uvs[i]);
  45059. }
  45060. return shapeUV;
  45061. };
  45062. // adds a new particle object in the particles array
  45063. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  45064. if (bInfo === void 0) { bInfo = null; }
  45065. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  45066. this.particles.push(sp);
  45067. return sp;
  45068. };
  45069. /**
  45070. * Adds some particles to the SPS from the model shape. Returns the shape id.
  45071. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  45072. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  45073. * `nb` (positive integer) the number of particles to be created from this model
  45074. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  45075. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  45076. */
  45077. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  45078. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45079. var meshInd = mesh.getIndices();
  45080. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45081. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45082. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45083. var bbInfo;
  45084. if (this._particlesIntersect) {
  45085. bbInfo = mesh.getBoundingInfo();
  45086. }
  45087. var shape = this._posToShape(meshPos);
  45088. var shapeUV = this._uvsToShapeUV(meshUV);
  45089. var posfunc = options ? options.positionFunction : null;
  45090. var vtxfunc = options ? options.vertexFunction : null;
  45091. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  45092. // particles
  45093. var sp;
  45094. var currentCopy;
  45095. var idx = this.nbParticles;
  45096. for (var i = 0; i < nb; i++) {
  45097. var currentPos = this._positions.length;
  45098. var currentInd = this._indices.length;
  45099. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  45100. if (this._updatable) {
  45101. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  45102. sp.position.copyFrom(currentCopy.position);
  45103. sp.rotation.copyFrom(currentCopy.rotation);
  45104. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  45105. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  45106. }
  45107. if (currentCopy.color && sp.color) {
  45108. sp.color.copyFrom(currentCopy.color);
  45109. }
  45110. sp.scaling.copyFrom(currentCopy.scaling);
  45111. sp.uvs.copyFrom(currentCopy.uvs);
  45112. }
  45113. this._index += shape.length;
  45114. idx++;
  45115. }
  45116. this.nbParticles += nb;
  45117. this._shapeCounter++;
  45118. return this._shapeCounter - 1;
  45119. };
  45120. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  45121. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  45122. this._resetCopy();
  45123. if (particle._model._positionFunction) {
  45124. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  45125. }
  45126. if (this._copy.rotationQuaternion) {
  45127. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45128. }
  45129. else {
  45130. this._yaw = this._copy.rotation.y;
  45131. this._pitch = this._copy.rotation.x;
  45132. this._roll = this._copy.rotation.z;
  45133. this._quaternionRotationYPR();
  45134. }
  45135. this._quaternionToRotationMatrix();
  45136. this._shape = particle._model._shape;
  45137. for (var pt = 0; pt < this._shape.length; pt++) {
  45138. this._vertex.x = this._shape[pt].x;
  45139. this._vertex.y = this._shape[pt].y;
  45140. this._vertex.z = this._shape[pt].z;
  45141. if (particle._model._vertexFunction) {
  45142. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  45143. }
  45144. this._vertex.x *= this._copy.scaling.x;
  45145. this._vertex.y *= this._copy.scaling.y;
  45146. this._vertex.z *= this._copy.scaling.z;
  45147. this._vertex.x += this._copy.pivot.x;
  45148. this._vertex.y += this._copy.pivot.y;
  45149. this._vertex.z += this._copy.pivot.z;
  45150. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45151. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  45152. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  45153. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  45154. }
  45155. particle.position.x = 0.0;
  45156. particle.position.y = 0.0;
  45157. particle.position.z = 0.0;
  45158. particle.rotation.x = 0.0;
  45159. particle.rotation.y = 0.0;
  45160. particle.rotation.z = 0.0;
  45161. particle.rotationQuaternion = null;
  45162. particle.scaling.x = 1.0;
  45163. particle.scaling.y = 1.0;
  45164. particle.scaling.z = 1.0;
  45165. };
  45166. /**
  45167. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45168. * Returns the SPS.
  45169. */
  45170. SolidParticleSystem.prototype.rebuildMesh = function () {
  45171. for (var p = 0; p < this.particles.length; p++) {
  45172. this._rebuildParticle(this.particles[p]);
  45173. }
  45174. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45175. return this;
  45176. };
  45177. /**
  45178. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45179. * This method calls `updateParticle()` for each particle of the SPS.
  45180. * For an animated SPS, it is usually called within the render loop.
  45181. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45182. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45183. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45184. * Returns the SPS.
  45185. */
  45186. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45187. if (start === void 0) { start = 0; }
  45188. if (end === void 0) { end = this.nbParticles - 1; }
  45189. if (update === void 0) { update = true; }
  45190. if (!this._updatable) {
  45191. return this;
  45192. }
  45193. // custom beforeUpdate
  45194. this.beforeUpdateParticles(start, end, update);
  45195. this._cam_axisX.x = 1.0;
  45196. this._cam_axisX.y = 0.0;
  45197. this._cam_axisX.z = 0.0;
  45198. this._cam_axisY.x = 0.0;
  45199. this._cam_axisY.y = 1.0;
  45200. this._cam_axisY.z = 0.0;
  45201. this._cam_axisZ.x = 0.0;
  45202. this._cam_axisZ.y = 0.0;
  45203. this._cam_axisZ.z = 1.0;
  45204. // cases when the World Matrix is to be computed first
  45205. if (this.billboard || this._depthSort) {
  45206. this.mesh.computeWorldMatrix(true);
  45207. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45208. }
  45209. // if the particles will always face the camera
  45210. if (this.billboard) {
  45211. // compute the camera position and un-rotate it by the current mesh rotation
  45212. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45213. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45214. this._cam_axisZ.normalize();
  45215. // same for camera up vector extracted from the cam view matrix
  45216. var view = this._camera.getViewMatrix(true);
  45217. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45218. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45219. this._cam_axisY.normalize();
  45220. this._cam_axisX.normalize();
  45221. }
  45222. // if depthSort, compute the camera global position in the mesh local system
  45223. if (this._depthSort) {
  45224. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45225. }
  45226. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45227. var idx = 0; // current position index in the global array positions32
  45228. var index = 0; // position start index in the global array positions32 of the current particle
  45229. var colidx = 0; // current color index in the global array colors32
  45230. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45231. var uvidx = 0; // current uv index in the global array uvs32
  45232. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45233. var pt = 0; // current index in the particle model shape
  45234. if (this.mesh.isFacetDataEnabled) {
  45235. this._computeBoundingBox = true;
  45236. }
  45237. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45238. if (this._computeBoundingBox) {
  45239. if (start == 0 && end == this.nbParticles - 1) {
  45240. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45241. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45242. }
  45243. else {
  45244. if (this.mesh._boundingInfo) {
  45245. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45246. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45247. }
  45248. }
  45249. }
  45250. // particle loop
  45251. index = this.particles[start]._pos;
  45252. var vpos = (index / 3) | 0;
  45253. colorIndex = vpos * 4;
  45254. uvIndex = vpos * 2;
  45255. for (var p = start; p <= end; p++) {
  45256. this._particle = this.particles[p];
  45257. this._shape = this._particle._model._shape;
  45258. this._shapeUV = this._particle._model._shapeUV;
  45259. // call to custom user function to update the particle properties
  45260. this.updateParticle(this._particle);
  45261. // camera-particle distance for depth sorting
  45262. if (this._depthSort && this._depthSortParticles) {
  45263. var dsp = this.depthSortedParticles[p];
  45264. dsp.ind = this._particle._ind;
  45265. dsp.indicesLength = this._particle._model._indicesLength;
  45266. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45267. }
  45268. // skip the computations for inactive or already invisible particles
  45269. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45270. // increment indexes for the next particle
  45271. pt = this._shape.length;
  45272. index += pt * 3;
  45273. colorIndex += pt * 4;
  45274. uvIndex += pt * 2;
  45275. continue;
  45276. }
  45277. if (this._particle.isVisible) {
  45278. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45279. // particle rotation matrix
  45280. if (this.billboard) {
  45281. this._particle.rotation.x = 0.0;
  45282. this._particle.rotation.y = 0.0;
  45283. }
  45284. if (this._computeParticleRotation || this.billboard) {
  45285. if (this._particle.rotationQuaternion) {
  45286. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45287. }
  45288. else {
  45289. this._yaw = this._particle.rotation.y;
  45290. this._pitch = this._particle.rotation.x;
  45291. this._roll = this._particle.rotation.z;
  45292. this._quaternionRotationYPR();
  45293. }
  45294. this._quaternionToRotationMatrix();
  45295. }
  45296. // particle vertex loop
  45297. for (pt = 0; pt < this._shape.length; pt++) {
  45298. idx = index + pt * 3;
  45299. colidx = colorIndex + pt * 4;
  45300. uvidx = uvIndex + pt * 2;
  45301. this._vertex.x = this._shape[pt].x;
  45302. this._vertex.y = this._shape[pt].y;
  45303. this._vertex.z = this._shape[pt].z;
  45304. if (this._computeParticleVertex) {
  45305. this.updateParticleVertex(this._particle, this._vertex, pt);
  45306. }
  45307. // positions
  45308. this._vertex.x *= this._particle.scaling.x;
  45309. this._vertex.y *= this._particle.scaling.y;
  45310. this._vertex.z *= this._particle.scaling.z;
  45311. this._vertex.x += this._particle.pivot.x;
  45312. this._vertex.y += this._particle.pivot.y;
  45313. this._vertex.z += this._particle.pivot.z;
  45314. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45315. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45316. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45317. 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;
  45318. 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;
  45319. 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;
  45320. if (this._computeBoundingBox) {
  45321. if (this._positions32[idx] < this._minimum.x) {
  45322. this._minimum.x = this._positions32[idx];
  45323. }
  45324. if (this._positions32[idx] > this._maximum.x) {
  45325. this._maximum.x = this._positions32[idx];
  45326. }
  45327. if (this._positions32[idx + 1] < this._minimum.y) {
  45328. this._minimum.y = this._positions32[idx + 1];
  45329. }
  45330. if (this._positions32[idx + 1] > this._maximum.y) {
  45331. this._maximum.y = this._positions32[idx + 1];
  45332. }
  45333. if (this._positions32[idx + 2] < this._minimum.z) {
  45334. this._minimum.z = this._positions32[idx + 2];
  45335. }
  45336. if (this._positions32[idx + 2] > this._maximum.z) {
  45337. this._maximum.z = this._positions32[idx + 2];
  45338. }
  45339. }
  45340. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  45341. if (!this._computeParticleVertex) {
  45342. this._normal.x = this._fixedNormal32[idx];
  45343. this._normal.y = this._fixedNormal32[idx + 1];
  45344. this._normal.z = this._fixedNormal32[idx + 2];
  45345. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  45346. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  45347. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  45348. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  45349. 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;
  45350. 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;
  45351. }
  45352. if (this._computeParticleColor && this._particle.color) {
  45353. this._colors32[colidx] = this._particle.color.r;
  45354. this._colors32[colidx + 1] = this._particle.color.g;
  45355. this._colors32[colidx + 2] = this._particle.color.b;
  45356. this._colors32[colidx + 3] = this._particle.color.a;
  45357. }
  45358. if (this._computeParticleTexture) {
  45359. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45360. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45361. }
  45362. }
  45363. }
  45364. else {
  45365. this._particle._stillInvisible = true; // mark the particle as invisible
  45366. for (pt = 0; pt < this._shape.length; pt++) {
  45367. idx = index + pt * 3;
  45368. colidx = colorIndex + pt * 4;
  45369. uvidx = uvIndex + pt * 2;
  45370. this._positions32[idx] = 0.0;
  45371. this._positions32[idx + 1] = 0.0;
  45372. this._positions32[idx + 2] = 0.0;
  45373. this._normals32[idx] = 0.0;
  45374. this._normals32[idx + 1] = 0.0;
  45375. this._normals32[idx + 2] = 0.0;
  45376. if (this._computeParticleColor && this._particle.color) {
  45377. this._colors32[colidx] = this._particle.color.r;
  45378. this._colors32[colidx + 1] = this._particle.color.g;
  45379. this._colors32[colidx + 2] = this._particle.color.b;
  45380. this._colors32[colidx + 3] = this._particle.color.a;
  45381. }
  45382. if (this._computeParticleTexture) {
  45383. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45384. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45385. }
  45386. }
  45387. }
  45388. // if the particle intersections must be computed : update the bbInfo
  45389. if (this._particlesIntersect) {
  45390. var bInfo = this._particle._boundingInfo;
  45391. var bBox = bInfo.boundingBox;
  45392. var bSphere = bInfo.boundingSphere;
  45393. if (!this._bSphereOnly) {
  45394. // place, scale and rotate the particle bbox within the SPS local system, then update it
  45395. for (var b = 0; b < bBox.vectors.length; b++) {
  45396. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  45397. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  45398. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  45399. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45400. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45401. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45402. 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;
  45403. 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;
  45404. 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;
  45405. }
  45406. bBox._update(this.mesh._worldMatrix);
  45407. }
  45408. // place and scale the particle bouding sphere in the SPS local system, then update it
  45409. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  45410. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  45411. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  45412. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  45413. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  45414. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  45415. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  45416. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  45417. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  45418. 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));
  45419. bSphere._update(this.mesh._worldMatrix);
  45420. }
  45421. // increment indexes for the next particle
  45422. index = idx + 3;
  45423. colorIndex = colidx + 4;
  45424. uvIndex = uvidx + 2;
  45425. }
  45426. // if the VBO must be updated
  45427. if (update) {
  45428. if (this._computeParticleColor) {
  45429. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  45430. }
  45431. if (this._computeParticleTexture) {
  45432. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  45433. }
  45434. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45435. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  45436. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  45437. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  45438. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  45439. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  45440. for (var i = 0; i < this._normals32.length; i++) {
  45441. this._fixedNormal32[i] = this._normals32[i];
  45442. }
  45443. }
  45444. if (!this.mesh.areNormalsFrozen) {
  45445. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  45446. }
  45447. }
  45448. if (this._depthSort && this._depthSortParticles) {
  45449. this.depthSortedParticles.sort(this._depthSortFunction);
  45450. var dspl = this.depthSortedParticles.length;
  45451. var sorted = 0;
  45452. var lind = 0;
  45453. var sind = 0;
  45454. var sid = 0;
  45455. for (sorted = 0; sorted < dspl; sorted++) {
  45456. lind = this.depthSortedParticles[sorted].indicesLength;
  45457. sind = this.depthSortedParticles[sorted].ind;
  45458. for (var i = 0; i < lind; i++) {
  45459. this._indices32[sid] = this._indices[sind + i];
  45460. sid++;
  45461. }
  45462. }
  45463. this.mesh.updateIndices(this._indices32);
  45464. }
  45465. }
  45466. if (this._computeBoundingBox) {
  45467. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  45468. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  45469. }
  45470. this.afterUpdateParticles(start, end, update);
  45471. return this;
  45472. };
  45473. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  45474. this._halfroll = this._roll * 0.5;
  45475. this._halfpitch = this._pitch * 0.5;
  45476. this._halfyaw = this._yaw * 0.5;
  45477. this._sinRoll = Math.sin(this._halfroll);
  45478. this._cosRoll = Math.cos(this._halfroll);
  45479. this._sinPitch = Math.sin(this._halfpitch);
  45480. this._cosPitch = Math.cos(this._halfpitch);
  45481. this._sinYaw = Math.sin(this._halfyaw);
  45482. this._cosYaw = Math.cos(this._halfyaw);
  45483. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  45484. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  45485. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  45486. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  45487. };
  45488. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  45489. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  45490. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  45491. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  45492. this._rotMatrix.m[3] = 0;
  45493. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  45494. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  45495. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  45496. this._rotMatrix.m[7] = 0;
  45497. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  45498. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  45499. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  45500. this._rotMatrix.m[11] = 0;
  45501. this._rotMatrix.m[12] = 0;
  45502. this._rotMatrix.m[13] = 0;
  45503. this._rotMatrix.m[14] = 0;
  45504. this._rotMatrix.m[15] = 1.0;
  45505. };
  45506. /**
  45507. * Disposes the SPS.
  45508. * Returns nothing.
  45509. */
  45510. SolidParticleSystem.prototype.dispose = function () {
  45511. this.mesh.dispose();
  45512. this.vars = null;
  45513. // drop references to internal big arrays for the GC
  45514. this._positions = null;
  45515. this._indices = null;
  45516. this._normals = null;
  45517. this._uvs = null;
  45518. this._colors = null;
  45519. this._indices32 = null;
  45520. this._positions32 = null;
  45521. this._normals32 = null;
  45522. this._fixedNormal32 = null;
  45523. this._uvs32 = null;
  45524. this._colors32 = null;
  45525. this.pickedParticles = null;
  45526. };
  45527. /**
  45528. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  45529. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45530. * Returns the SPS.
  45531. */
  45532. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  45533. if (!this._isVisibilityBoxLocked) {
  45534. this.mesh.refreshBoundingInfo();
  45535. }
  45536. return this;
  45537. };
  45538. /**
  45539. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  45540. * @param size the size (float) of the visibility box
  45541. * note : this doesn't lock the SPS mesh bounding box.
  45542. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45543. */
  45544. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  45545. var vis = size / 2;
  45546. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  45547. };
  45548. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  45549. // getter and setter
  45550. get: function () {
  45551. return this._alwaysVisible;
  45552. },
  45553. /**
  45554. * Sets the SPS as always visible or not
  45555. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45556. */
  45557. set: function (val) {
  45558. this._alwaysVisible = val;
  45559. this.mesh.alwaysSelectAsActiveMesh = val;
  45560. },
  45561. enumerable: true,
  45562. configurable: true
  45563. });
  45564. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  45565. get: function () {
  45566. return this._isVisibilityBoxLocked;
  45567. },
  45568. /**
  45569. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  45570. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45571. */
  45572. set: function (val) {
  45573. this._isVisibilityBoxLocked = val;
  45574. var boundingInfo = this.mesh.getBoundingInfo();
  45575. if (boundingInfo) {
  45576. boundingInfo.isLocked = val;
  45577. }
  45578. },
  45579. enumerable: true,
  45580. configurable: true
  45581. });
  45582. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  45583. // getters
  45584. get: function () {
  45585. return this._computeParticleRotation;
  45586. },
  45587. // Optimizer setters
  45588. /**
  45589. * Tells to `setParticles()` to compute the particle rotations or not.
  45590. * Default value : true. The SPS is faster when it's set to false.
  45591. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  45592. */
  45593. set: function (val) {
  45594. this._computeParticleRotation = val;
  45595. },
  45596. enumerable: true,
  45597. configurable: true
  45598. });
  45599. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  45600. get: function () {
  45601. return this._computeParticleColor;
  45602. },
  45603. /**
  45604. * Tells to `setParticles()` to compute the particle colors or not.
  45605. * Default value : true. The SPS is faster when it's set to false.
  45606. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  45607. */
  45608. set: function (val) {
  45609. this._computeParticleColor = val;
  45610. },
  45611. enumerable: true,
  45612. configurable: true
  45613. });
  45614. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  45615. get: function () {
  45616. return this._computeParticleTexture;
  45617. },
  45618. /**
  45619. * Tells to `setParticles()` to compute the particle textures or not.
  45620. * Default value : true. The SPS is faster when it's set to false.
  45621. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  45622. */
  45623. set: function (val) {
  45624. this._computeParticleTexture = val;
  45625. },
  45626. enumerable: true,
  45627. configurable: true
  45628. });
  45629. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  45630. get: function () {
  45631. return this._computeParticleVertex;
  45632. },
  45633. /**
  45634. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  45635. * Default value : false. The SPS is faster when it's set to false.
  45636. * Note : the particle custom vertex positions aren't stored values.
  45637. */
  45638. set: function (val) {
  45639. this._computeParticleVertex = val;
  45640. },
  45641. enumerable: true,
  45642. configurable: true
  45643. });
  45644. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  45645. get: function () {
  45646. return this._computeBoundingBox;
  45647. },
  45648. /**
  45649. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  45650. */
  45651. set: function (val) {
  45652. this._computeBoundingBox = val;
  45653. },
  45654. enumerable: true,
  45655. configurable: true
  45656. });
  45657. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  45658. get: function () {
  45659. return this._depthSortParticles;
  45660. },
  45661. /**
  45662. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  45663. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  45664. * Default : `true`
  45665. */
  45666. set: function (val) {
  45667. this._depthSortParticles = val;
  45668. },
  45669. enumerable: true,
  45670. configurable: true
  45671. });
  45672. // =======================================================================
  45673. // Particle behavior logic
  45674. // these following methods may be overwritten by the user to fit his needs
  45675. /**
  45676. * This function does nothing. It may be overwritten to set all the particle first values.
  45677. * The SPS doesn't call this function, you may have to call it by your own.
  45678. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45679. */
  45680. SolidParticleSystem.prototype.initParticles = function () {
  45681. };
  45682. /**
  45683. * This function does nothing. It may be overwritten to recycle a particle.
  45684. * The SPS doesn't call this function, you may have to call it by your own.
  45685. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45686. */
  45687. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  45688. return particle;
  45689. };
  45690. /**
  45691. * Updates a particle : this function should be overwritten by the user.
  45692. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  45693. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45694. * ex : just set a particle position or velocity and recycle conditions
  45695. */
  45696. SolidParticleSystem.prototype.updateParticle = function (particle) {
  45697. return particle;
  45698. };
  45699. /**
  45700. * Updates a vertex of a particle : it can be overwritten by the user.
  45701. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  45702. * @param particle the current particle
  45703. * @param vertex the current index of the current particle
  45704. * @param pt the index of the current vertex in the particle shape
  45705. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  45706. * ex : just set a vertex particle position
  45707. */
  45708. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  45709. return vertex;
  45710. };
  45711. /**
  45712. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  45713. * This does nothing and may be overwritten by the user.
  45714. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45715. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45716. * @param update the boolean update value actually passed to setParticles()
  45717. */
  45718. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  45719. };
  45720. /**
  45721. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  45722. * This will be passed three parameters.
  45723. * This does nothing and may be overwritten by the user.
  45724. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45725. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45726. * @param update the boolean update value actually passed to setParticles()
  45727. */
  45728. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  45729. };
  45730. return SolidParticleSystem;
  45731. }());
  45732. BABYLON.SolidParticleSystem = SolidParticleSystem;
  45733. })(BABYLON || (BABYLON = {}));
  45734. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  45735. var BABYLON;
  45736. (function (BABYLON) {
  45737. var GroundMesh = /** @class */ (function (_super) {
  45738. __extends(GroundMesh, _super);
  45739. function GroundMesh(name, scene) {
  45740. var _this = _super.call(this, name, scene) || this;
  45741. _this.generateOctree = false;
  45742. return _this;
  45743. }
  45744. GroundMesh.prototype.getClassName = function () {
  45745. return "GroundMesh";
  45746. };
  45747. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  45748. get: function () {
  45749. return Math.min(this._subdivisionsX, this._subdivisionsY);
  45750. },
  45751. enumerable: true,
  45752. configurable: true
  45753. });
  45754. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  45755. get: function () {
  45756. return this._subdivisionsX;
  45757. },
  45758. enumerable: true,
  45759. configurable: true
  45760. });
  45761. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  45762. get: function () {
  45763. return this._subdivisionsY;
  45764. },
  45765. enumerable: true,
  45766. configurable: true
  45767. });
  45768. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  45769. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  45770. this._subdivisionsX = chunksCount;
  45771. this._subdivisionsY = chunksCount;
  45772. this.subdivide(chunksCount);
  45773. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  45774. };
  45775. /**
  45776. * Returns a height (y) value in the Worl system :
  45777. * the ground altitude at the coordinates (x, z) expressed in the World system.
  45778. * Returns the ground y position if (x, z) are outside the ground surface.
  45779. */
  45780. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  45781. var world = this.getWorldMatrix();
  45782. var invMat = BABYLON.Tmp.Matrix[5];
  45783. world.invertToRef(invMat);
  45784. var tmpVect = BABYLON.Tmp.Vector3[8];
  45785. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  45786. x = tmpVect.x;
  45787. z = tmpVect.z;
  45788. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45789. return this.position.y;
  45790. }
  45791. if (!this._heightQuads || this._heightQuads.length == 0) {
  45792. this._initHeightQuads();
  45793. this._computeHeightQuads();
  45794. }
  45795. var facet = this._getFacetAt(x, z);
  45796. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  45797. // return y in the World system
  45798. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  45799. return tmpVect.y;
  45800. };
  45801. /**
  45802. * Returns a normalized vector (Vector3) orthogonal to the ground
  45803. * at the ground coordinates (x, z) expressed in the World system.
  45804. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  45805. */
  45806. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  45807. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  45808. this.getNormalAtCoordinatesToRef(x, z, normal);
  45809. return normal;
  45810. };
  45811. /**
  45812. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  45813. * at the ground coordinates (x, z) expressed in the World system.
  45814. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  45815. * Returns the GroundMesh.
  45816. */
  45817. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  45818. var world = this.getWorldMatrix();
  45819. var tmpMat = BABYLON.Tmp.Matrix[5];
  45820. world.invertToRef(tmpMat);
  45821. var tmpVect = BABYLON.Tmp.Vector3[8];
  45822. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  45823. x = tmpVect.x;
  45824. z = tmpVect.z;
  45825. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45826. return this;
  45827. }
  45828. if (!this._heightQuads || this._heightQuads.length == 0) {
  45829. this._initHeightQuads();
  45830. this._computeHeightQuads();
  45831. }
  45832. var facet = this._getFacetAt(x, z);
  45833. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  45834. return this;
  45835. };
  45836. /**
  45837. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  45838. * if the ground has been updated.
  45839. * This can be used in the render loop.
  45840. * Returns the GroundMesh.
  45841. */
  45842. GroundMesh.prototype.updateCoordinateHeights = function () {
  45843. if (!this._heightQuads || this._heightQuads.length == 0) {
  45844. this._initHeightQuads();
  45845. }
  45846. this._computeHeightQuads();
  45847. return this;
  45848. };
  45849. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  45850. GroundMesh.prototype._getFacetAt = function (x, z) {
  45851. // retrieve col and row from x, z coordinates in the ground local system
  45852. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  45853. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  45854. var quad = this._heightQuads[row * this._subdivisionsX + col];
  45855. var facet;
  45856. if (z < quad.slope.x * x + quad.slope.y) {
  45857. facet = quad.facet1;
  45858. }
  45859. else {
  45860. facet = quad.facet2;
  45861. }
  45862. return facet;
  45863. };
  45864. // Creates and populates the heightMap array with "facet" elements :
  45865. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  45866. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45867. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45868. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45869. // Returns the GroundMesh.
  45870. GroundMesh.prototype._initHeightQuads = function () {
  45871. var subdivisionsX = this._subdivisionsX;
  45872. var subdivisionsY = this._subdivisionsY;
  45873. this._heightQuads = new Array();
  45874. for (var row = 0; row < subdivisionsY; row++) {
  45875. for (var col = 0; col < subdivisionsX; col++) {
  45876. 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) };
  45877. this._heightQuads[row * subdivisionsX + col] = quad;
  45878. }
  45879. }
  45880. return this;
  45881. };
  45882. // Compute each quad element values and update the the heightMap array :
  45883. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45884. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45885. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45886. // Returns the GroundMesh.
  45887. GroundMesh.prototype._computeHeightQuads = function () {
  45888. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45889. if (!positions) {
  45890. return this;
  45891. }
  45892. var v1 = BABYLON.Tmp.Vector3[3];
  45893. var v2 = BABYLON.Tmp.Vector3[2];
  45894. var v3 = BABYLON.Tmp.Vector3[1];
  45895. var v4 = BABYLON.Tmp.Vector3[0];
  45896. var v1v2 = BABYLON.Tmp.Vector3[4];
  45897. var v1v3 = BABYLON.Tmp.Vector3[5];
  45898. var v1v4 = BABYLON.Tmp.Vector3[6];
  45899. var norm1 = BABYLON.Tmp.Vector3[7];
  45900. var norm2 = BABYLON.Tmp.Vector3[8];
  45901. var i = 0;
  45902. var j = 0;
  45903. var k = 0;
  45904. var cd = 0; // 2D slope coefficient : z = cd * x + h
  45905. var h = 0;
  45906. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  45907. var d2 = 0;
  45908. var subdivisionsX = this._subdivisionsX;
  45909. var subdivisionsY = this._subdivisionsY;
  45910. for (var row = 0; row < subdivisionsY; row++) {
  45911. for (var col = 0; col < subdivisionsX; col++) {
  45912. i = col * 3;
  45913. j = row * (subdivisionsX + 1) * 3;
  45914. k = (row + 1) * (subdivisionsX + 1) * 3;
  45915. v1.x = positions[j + i];
  45916. v1.y = positions[j + i + 1];
  45917. v1.z = positions[j + i + 2];
  45918. v2.x = positions[j + i + 3];
  45919. v2.y = positions[j + i + 4];
  45920. v2.z = positions[j + i + 5];
  45921. v3.x = positions[k + i];
  45922. v3.y = positions[k + i + 1];
  45923. v3.z = positions[k + i + 2];
  45924. v4.x = positions[k + i + 3];
  45925. v4.y = positions[k + i + 4];
  45926. v4.z = positions[k + i + 5];
  45927. // 2D slope V1V4
  45928. cd = (v4.z - v1.z) / (v4.x - v1.x);
  45929. h = v1.z - cd * v1.x; // v1 belongs to the slope
  45930. // facet equations :
  45931. // we compute each facet normal vector
  45932. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  45933. // we compute the value d by applying the equation to v1 which belongs to the plane
  45934. // then we store the facet equation in a Vector4
  45935. v2.subtractToRef(v1, v1v2);
  45936. v3.subtractToRef(v1, v1v3);
  45937. v4.subtractToRef(v1, v1v4);
  45938. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  45939. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  45940. norm1.normalize();
  45941. norm2.normalize();
  45942. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  45943. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  45944. var quad = this._heightQuads[row * subdivisionsX + col];
  45945. quad.slope.copyFromFloats(cd, h);
  45946. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  45947. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  45948. }
  45949. }
  45950. return this;
  45951. };
  45952. GroundMesh.prototype.serialize = function (serializationObject) {
  45953. _super.prototype.serialize.call(this, serializationObject);
  45954. serializationObject.subdivisionsX = this._subdivisionsX;
  45955. serializationObject.subdivisionsY = this._subdivisionsY;
  45956. serializationObject.minX = this._minX;
  45957. serializationObject.maxX = this._maxX;
  45958. serializationObject.minZ = this._minZ;
  45959. serializationObject.maxZ = this._maxZ;
  45960. serializationObject.width = this._width;
  45961. serializationObject.height = this._height;
  45962. };
  45963. GroundMesh.Parse = function (parsedMesh, scene) {
  45964. var result = new GroundMesh(parsedMesh.name, scene);
  45965. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  45966. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  45967. result._minX = parsedMesh.minX;
  45968. result._maxX = parsedMesh.maxX;
  45969. result._minZ = parsedMesh.minZ;
  45970. result._maxZ = parsedMesh.maxZ;
  45971. result._width = parsedMesh.width;
  45972. result._height = parsedMesh.height;
  45973. return result;
  45974. };
  45975. return GroundMesh;
  45976. }(BABYLON.Mesh));
  45977. BABYLON.GroundMesh = GroundMesh;
  45978. })(BABYLON || (BABYLON = {}));
  45979. //# sourceMappingURL=babylon.groundMesh.js.map
  45980. var BABYLON;
  45981. (function (BABYLON) {
  45982. /**
  45983. * Creates an instance based on a source mesh.
  45984. */
  45985. var InstancedMesh = /** @class */ (function (_super) {
  45986. __extends(InstancedMesh, _super);
  45987. function InstancedMesh(name, source) {
  45988. var _this = _super.call(this, name, source.getScene()) || this;
  45989. source.instances.push(_this);
  45990. _this._sourceMesh = source;
  45991. _this.position.copyFrom(source.position);
  45992. _this.rotation.copyFrom(source.rotation);
  45993. _this.scaling.copyFrom(source.scaling);
  45994. if (source.rotationQuaternion) {
  45995. _this.rotationQuaternion = source.rotationQuaternion.clone();
  45996. }
  45997. _this.infiniteDistance = source.infiniteDistance;
  45998. _this.setPivotMatrix(source.getPivotMatrix());
  45999. _this.refreshBoundingInfo();
  46000. _this._syncSubMeshes();
  46001. return _this;
  46002. }
  46003. /**
  46004. * Returns the string "InstancedMesh".
  46005. */
  46006. InstancedMesh.prototype.getClassName = function () {
  46007. return "InstancedMesh";
  46008. };
  46009. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  46010. // Methods
  46011. get: function () {
  46012. return this._sourceMesh.receiveShadows;
  46013. },
  46014. enumerable: true,
  46015. configurable: true
  46016. });
  46017. Object.defineProperty(InstancedMesh.prototype, "material", {
  46018. get: function () {
  46019. return this._sourceMesh.material;
  46020. },
  46021. enumerable: true,
  46022. configurable: true
  46023. });
  46024. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  46025. get: function () {
  46026. return this._sourceMesh.visibility;
  46027. },
  46028. enumerable: true,
  46029. configurable: true
  46030. });
  46031. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  46032. get: function () {
  46033. return this._sourceMesh.skeleton;
  46034. },
  46035. enumerable: true,
  46036. configurable: true
  46037. });
  46038. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  46039. get: function () {
  46040. return this._sourceMesh.renderingGroupId;
  46041. },
  46042. enumerable: true,
  46043. configurable: true
  46044. });
  46045. /**
  46046. * Returns the total number of vertices (integer).
  46047. */
  46048. InstancedMesh.prototype.getTotalVertices = function () {
  46049. return this._sourceMesh.getTotalVertices();
  46050. };
  46051. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  46052. get: function () {
  46053. return this._sourceMesh;
  46054. },
  46055. enumerable: true,
  46056. configurable: true
  46057. });
  46058. /**
  46059. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  46060. */
  46061. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  46062. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  46063. };
  46064. /**
  46065. * Sets the vertex data of the mesh geometry for the requested `kind`.
  46066. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  46067. * The `data` are either a numeric array either a Float32Array.
  46068. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  46069. * 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).
  46070. * Note that a new underlying VertexBuffer object is created each call.
  46071. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  46072. *
  46073. * Possible `kind` values :
  46074. * - BABYLON.VertexBuffer.PositionKind
  46075. * - BABYLON.VertexBuffer.UVKind
  46076. * - BABYLON.VertexBuffer.UV2Kind
  46077. * - BABYLON.VertexBuffer.UV3Kind
  46078. * - BABYLON.VertexBuffer.UV4Kind
  46079. * - BABYLON.VertexBuffer.UV5Kind
  46080. * - BABYLON.VertexBuffer.UV6Kind
  46081. * - BABYLON.VertexBuffer.ColorKind
  46082. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46083. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46084. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46085. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46086. *
  46087. * Returns the Mesh.
  46088. */
  46089. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  46090. if (this.sourceMesh) {
  46091. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  46092. }
  46093. return this.sourceMesh;
  46094. };
  46095. /**
  46096. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  46097. * If the mesh has no geometry, it is simply returned as it is.
  46098. * The `data` are either a numeric array either a Float32Array.
  46099. * No new underlying VertexBuffer object is created.
  46100. * 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.
  46101. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  46102. *
  46103. * Possible `kind` values :
  46104. * - BABYLON.VertexBuffer.PositionKind
  46105. * - BABYLON.VertexBuffer.UVKind
  46106. * - BABYLON.VertexBuffer.UV2Kind
  46107. * - BABYLON.VertexBuffer.UV3Kind
  46108. * - BABYLON.VertexBuffer.UV4Kind
  46109. * - BABYLON.VertexBuffer.UV5Kind
  46110. * - BABYLON.VertexBuffer.UV6Kind
  46111. * - BABYLON.VertexBuffer.ColorKind
  46112. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46113. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46114. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46115. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46116. *
  46117. * Returns the Mesh.
  46118. */
  46119. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  46120. if (this.sourceMesh) {
  46121. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  46122. }
  46123. return this.sourceMesh;
  46124. };
  46125. /**
  46126. * Sets the mesh indices.
  46127. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  46128. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  46129. * This method creates a new index buffer each call.
  46130. * Returns the Mesh.
  46131. */
  46132. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  46133. if (totalVertices === void 0) { totalVertices = null; }
  46134. if (this.sourceMesh) {
  46135. this.sourceMesh.setIndices(indices, totalVertices);
  46136. }
  46137. return this.sourceMesh;
  46138. };
  46139. /**
  46140. * Boolean : True if the mesh owns the requested kind of data.
  46141. */
  46142. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  46143. return this._sourceMesh.isVerticesDataPresent(kind);
  46144. };
  46145. /**
  46146. * Returns an array of indices (IndicesArray).
  46147. */
  46148. InstancedMesh.prototype.getIndices = function () {
  46149. return this._sourceMesh.getIndices();
  46150. };
  46151. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  46152. get: function () {
  46153. return this._sourceMesh._positions;
  46154. },
  46155. enumerable: true,
  46156. configurable: true
  46157. });
  46158. /**
  46159. * Sets a new updated BoundingInfo to the mesh.
  46160. * Returns the mesh.
  46161. */
  46162. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46163. var meshBB = this._sourceMesh.getBoundingInfo();
  46164. if (meshBB) {
  46165. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46166. }
  46167. this._updateBoundingInfo();
  46168. return this;
  46169. };
  46170. InstancedMesh.prototype._preActivate = function () {
  46171. if (this._currentLOD) {
  46172. this._currentLOD._preActivate();
  46173. }
  46174. return this;
  46175. };
  46176. InstancedMesh.prototype._activate = function (renderId) {
  46177. if (this._currentLOD) {
  46178. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46179. }
  46180. return this;
  46181. };
  46182. /**
  46183. * Returns the current associated LOD AbstractMesh.
  46184. */
  46185. InstancedMesh.prototype.getLOD = function (camera) {
  46186. if (!camera) {
  46187. return this;
  46188. }
  46189. var boundingInfo = this.getBoundingInfo();
  46190. if (!boundingInfo) {
  46191. return this;
  46192. }
  46193. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46194. if (this._currentLOD === this.sourceMesh) {
  46195. return this;
  46196. }
  46197. return this._currentLOD;
  46198. };
  46199. InstancedMesh.prototype._syncSubMeshes = function () {
  46200. this.releaseSubMeshes();
  46201. if (this._sourceMesh.subMeshes) {
  46202. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46203. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46204. }
  46205. }
  46206. return this;
  46207. };
  46208. InstancedMesh.prototype._generatePointsArray = function () {
  46209. return this._sourceMesh._generatePointsArray();
  46210. };
  46211. /**
  46212. * Creates a new InstancedMesh from the current mesh.
  46213. * - name (string) : the cloned mesh name
  46214. * - newParent (optional Node) : the optional Node to parent the clone to.
  46215. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46216. *
  46217. * Returns the clone.
  46218. */
  46219. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46220. var result = this._sourceMesh.createInstance(name);
  46221. // Deep copy
  46222. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46223. // Bounding info
  46224. this.refreshBoundingInfo();
  46225. // Parent
  46226. if (newParent) {
  46227. result.parent = newParent;
  46228. }
  46229. if (!doNotCloneChildren) {
  46230. // Children
  46231. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46232. var mesh = this.getScene().meshes[index];
  46233. if (mesh.parent === this) {
  46234. mesh.clone(mesh.name, result);
  46235. }
  46236. }
  46237. }
  46238. result.computeWorldMatrix(true);
  46239. return result;
  46240. };
  46241. /**
  46242. * Disposes the InstancedMesh.
  46243. * Returns nothing.
  46244. */
  46245. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46246. // Remove from mesh
  46247. var index = this._sourceMesh.instances.indexOf(this);
  46248. this._sourceMesh.instances.splice(index, 1);
  46249. _super.prototype.dispose.call(this, doNotRecurse);
  46250. };
  46251. return InstancedMesh;
  46252. }(BABYLON.AbstractMesh));
  46253. BABYLON.InstancedMesh = InstancedMesh;
  46254. })(BABYLON || (BABYLON = {}));
  46255. //# sourceMappingURL=babylon.instancedMesh.js.map
  46256. var BABYLON;
  46257. (function (BABYLON) {
  46258. var LinesMesh = /** @class */ (function (_super) {
  46259. __extends(LinesMesh, _super);
  46260. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  46261. if (scene === void 0) { scene = null; }
  46262. if (parent === void 0) { parent = null; }
  46263. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46264. _this.useVertexColor = useVertexColor;
  46265. _this.color = new BABYLON.Color3(1, 1, 1);
  46266. _this.alpha = 1;
  46267. if (source) {
  46268. _this.color = source.color.clone();
  46269. _this.alpha = source.alpha;
  46270. _this.useVertexColor = source.useVertexColor;
  46271. }
  46272. _this._intersectionThreshold = 0.1;
  46273. var options = {
  46274. attributes: [BABYLON.VertexBuffer.PositionKind],
  46275. uniforms: ["world", "viewProjection"],
  46276. needAlphaBlending: false,
  46277. };
  46278. if (!useVertexColor) {
  46279. options.uniforms.push("color");
  46280. options.needAlphaBlending = true;
  46281. }
  46282. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46283. return _this;
  46284. }
  46285. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46286. /**
  46287. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46288. * This margin is expressed in world space coordinates, so its value may vary.
  46289. * Default value is 0.1
  46290. * @returns the intersection Threshold value.
  46291. */
  46292. get: function () {
  46293. return this._intersectionThreshold;
  46294. },
  46295. /**
  46296. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46297. * This margin is expressed in world space coordinates, so its value may vary.
  46298. * @param value the new threshold to apply
  46299. */
  46300. set: function (value) {
  46301. if (this._intersectionThreshold === value) {
  46302. return;
  46303. }
  46304. this._intersectionThreshold = value;
  46305. if (this.geometry) {
  46306. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46307. }
  46308. },
  46309. enumerable: true,
  46310. configurable: true
  46311. });
  46312. /**
  46313. * Returns the string "LineMesh"
  46314. */
  46315. LinesMesh.prototype.getClassName = function () {
  46316. return "LinesMesh";
  46317. };
  46318. Object.defineProperty(LinesMesh.prototype, "material", {
  46319. get: function () {
  46320. return this._colorShader;
  46321. },
  46322. enumerable: true,
  46323. configurable: true
  46324. });
  46325. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  46326. get: function () {
  46327. return false;
  46328. },
  46329. enumerable: true,
  46330. configurable: true
  46331. });
  46332. LinesMesh.prototype.createInstance = function (name) {
  46333. throw new Error("LinesMeshes do not support createInstance.");
  46334. };
  46335. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  46336. if (!this._geometry) {
  46337. return this;
  46338. }
  46339. // VBOs
  46340. this._geometry._bind(this._colorShader.getEffect());
  46341. // Color
  46342. if (!this.useVertexColor) {
  46343. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  46344. }
  46345. return this;
  46346. };
  46347. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  46348. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  46349. return this;
  46350. }
  46351. var engine = this.getScene().getEngine();
  46352. // Draw order
  46353. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  46354. return this;
  46355. };
  46356. LinesMesh.prototype.dispose = function (doNotRecurse) {
  46357. this._colorShader.dispose();
  46358. _super.prototype.dispose.call(this, doNotRecurse);
  46359. };
  46360. /**
  46361. * Returns a new LineMesh object cloned from the current one.
  46362. */
  46363. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46364. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  46365. };
  46366. return LinesMesh;
  46367. }(BABYLON.Mesh));
  46368. BABYLON.LinesMesh = LinesMesh;
  46369. })(BABYLON || (BABYLON = {}));
  46370. //# sourceMappingURL=babylon.linesMesh.js.map
  46371. var BABYLON;
  46372. (function (BABYLON) {
  46373. var ShaderMaterial = /** @class */ (function (_super) {
  46374. __extends(ShaderMaterial, _super);
  46375. function ShaderMaterial(name, scene, shaderPath, options) {
  46376. var _this = _super.call(this, name, scene) || this;
  46377. _this._textures = {};
  46378. _this._textureArrays = {};
  46379. _this._floats = {};
  46380. _this._floatsArrays = {};
  46381. _this._colors3 = {};
  46382. _this._colors3Arrays = {};
  46383. _this._colors4 = {};
  46384. _this._vectors2 = {};
  46385. _this._vectors3 = {};
  46386. _this._vectors4 = {};
  46387. _this._matrices = {};
  46388. _this._matrices3x3 = {};
  46389. _this._matrices2x2 = {};
  46390. _this._vectors3Arrays = {};
  46391. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46392. _this._shaderPath = shaderPath;
  46393. options.needAlphaBlending = options.needAlphaBlending || false;
  46394. options.needAlphaTesting = options.needAlphaTesting || false;
  46395. options.attributes = options.attributes || ["position", "normal", "uv"];
  46396. options.uniforms = options.uniforms || ["worldViewProjection"];
  46397. options.uniformBuffers = options.uniformBuffers || [];
  46398. options.samplers = options.samplers || [];
  46399. options.defines = options.defines || [];
  46400. _this._options = options;
  46401. return _this;
  46402. }
  46403. ShaderMaterial.prototype.getClassName = function () {
  46404. return "ShaderMaterial";
  46405. };
  46406. ShaderMaterial.prototype.needAlphaBlending = function () {
  46407. return this._options.needAlphaBlending;
  46408. };
  46409. ShaderMaterial.prototype.needAlphaTesting = function () {
  46410. return this._options.needAlphaTesting;
  46411. };
  46412. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46413. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46414. this._options.uniforms.push(uniformName);
  46415. }
  46416. };
  46417. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46418. if (this._options.samplers.indexOf(name) === -1) {
  46419. this._options.samplers.push(name);
  46420. }
  46421. this._textures[name] = texture;
  46422. return this;
  46423. };
  46424. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46425. if (this._options.samplers.indexOf(name) === -1) {
  46426. this._options.samplers.push(name);
  46427. }
  46428. this._checkUniform(name);
  46429. this._textureArrays[name] = textures;
  46430. return this;
  46431. };
  46432. ShaderMaterial.prototype.setFloat = function (name, value) {
  46433. this._checkUniform(name);
  46434. this._floats[name] = value;
  46435. return this;
  46436. };
  46437. ShaderMaterial.prototype.setFloats = function (name, value) {
  46438. this._checkUniform(name);
  46439. this._floatsArrays[name] = value;
  46440. return this;
  46441. };
  46442. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46443. this._checkUniform(name);
  46444. this._colors3[name] = value;
  46445. return this;
  46446. };
  46447. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  46448. this._checkUniform(name);
  46449. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  46450. color.toArray(arr, arr.length);
  46451. return arr;
  46452. }, []);
  46453. return this;
  46454. };
  46455. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46456. this._checkUniform(name);
  46457. this._colors4[name] = value;
  46458. return this;
  46459. };
  46460. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46461. this._checkUniform(name);
  46462. this._vectors2[name] = value;
  46463. return this;
  46464. };
  46465. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46466. this._checkUniform(name);
  46467. this._vectors3[name] = value;
  46468. return this;
  46469. };
  46470. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46471. this._checkUniform(name);
  46472. this._vectors4[name] = value;
  46473. return this;
  46474. };
  46475. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46476. this._checkUniform(name);
  46477. this._matrices[name] = value;
  46478. return this;
  46479. };
  46480. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46481. this._checkUniform(name);
  46482. this._matrices3x3[name] = value;
  46483. return this;
  46484. };
  46485. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46486. this._checkUniform(name);
  46487. this._matrices2x2[name] = value;
  46488. return this;
  46489. };
  46490. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46491. this._checkUniform(name);
  46492. this._vectors3Arrays[name] = value;
  46493. return this;
  46494. };
  46495. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46496. if (!mesh) {
  46497. return true;
  46498. }
  46499. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46500. return false;
  46501. }
  46502. return false;
  46503. };
  46504. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46505. var scene = this.getScene();
  46506. var engine = scene.getEngine();
  46507. if (!this.checkReadyOnEveryCall) {
  46508. if (this._renderId === scene.getRenderId()) {
  46509. if (this._checkCache(scene, mesh, useInstances)) {
  46510. return true;
  46511. }
  46512. }
  46513. }
  46514. // Instances
  46515. var defines = [];
  46516. var attribs = [];
  46517. var fallbacks = new BABYLON.EffectFallbacks();
  46518. if (useInstances) {
  46519. defines.push("#define INSTANCES");
  46520. }
  46521. for (var index = 0; index < this._options.defines.length; index++) {
  46522. defines.push(this._options.defines[index]);
  46523. }
  46524. for (var index = 0; index < this._options.attributes.length; index++) {
  46525. attribs.push(this._options.attributes[index]);
  46526. }
  46527. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  46528. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46529. defines.push("#define VERTEXCOLOR");
  46530. }
  46531. // Bones
  46532. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  46533. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46534. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46535. if (mesh.numBoneInfluencers > 4) {
  46536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46538. }
  46539. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46540. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46541. fallbacks.addCPUSkinningFallback(0, mesh);
  46542. if (this._options.uniforms.indexOf("mBones") === -1) {
  46543. this._options.uniforms.push("mBones");
  46544. }
  46545. }
  46546. else {
  46547. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46548. }
  46549. // Textures
  46550. for (var name in this._textures) {
  46551. if (!this._textures[name].isReady()) {
  46552. return false;
  46553. }
  46554. }
  46555. // Alpha test
  46556. if (engine.getAlphaTesting()) {
  46557. defines.push("#define ALPHATEST");
  46558. }
  46559. var previousEffect = this._effect;
  46560. var join = defines.join("\n");
  46561. this._effect = engine.createEffect(this._shaderPath, {
  46562. attributes: attribs,
  46563. uniformsNames: this._options.uniforms,
  46564. uniformBuffersNames: this._options.uniformBuffers,
  46565. samplers: this._options.samplers,
  46566. defines: join,
  46567. fallbacks: fallbacks,
  46568. onCompiled: this.onCompiled,
  46569. onError: this.onError
  46570. }, engine);
  46571. if (!this._effect.isReady()) {
  46572. return false;
  46573. }
  46574. if (previousEffect !== this._effect) {
  46575. scene.resetCachedMaterial();
  46576. }
  46577. this._renderId = scene.getRenderId();
  46578. return true;
  46579. };
  46580. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46581. var scene = this.getScene();
  46582. if (!this._effect) {
  46583. return;
  46584. }
  46585. if (this._options.uniforms.indexOf("world") !== -1) {
  46586. this._effect.setMatrix("world", world);
  46587. }
  46588. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46589. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46590. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46591. }
  46592. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46593. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46594. }
  46595. };
  46596. ShaderMaterial.prototype.bind = function (world, mesh) {
  46597. // Std values
  46598. this.bindOnlyWorldMatrix(world);
  46599. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  46600. if (this._options.uniforms.indexOf("view") !== -1) {
  46601. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46602. }
  46603. if (this._options.uniforms.indexOf("projection") !== -1) {
  46604. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46605. }
  46606. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46607. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46608. }
  46609. // Bones
  46610. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46611. var name;
  46612. // Texture
  46613. for (name in this._textures) {
  46614. this._effect.setTexture(name, this._textures[name]);
  46615. }
  46616. // Texture arrays
  46617. for (name in this._textureArrays) {
  46618. this._effect.setTextureArray(name, this._textureArrays[name]);
  46619. }
  46620. // Float
  46621. for (name in this._floats) {
  46622. this._effect.setFloat(name, this._floats[name]);
  46623. }
  46624. // Float s
  46625. for (name in this._floatsArrays) {
  46626. this._effect.setArray(name, this._floatsArrays[name]);
  46627. }
  46628. // Color3
  46629. for (name in this._colors3) {
  46630. this._effect.setColor3(name, this._colors3[name]);
  46631. }
  46632. for (name in this._colors3Arrays) {
  46633. this._effect.setArray3(name, this._colors3Arrays[name]);
  46634. }
  46635. // Color4
  46636. for (name in this._colors4) {
  46637. var color = this._colors4[name];
  46638. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46639. }
  46640. // Vector2
  46641. for (name in this._vectors2) {
  46642. this._effect.setVector2(name, this._vectors2[name]);
  46643. }
  46644. // Vector3
  46645. for (name in this._vectors3) {
  46646. this._effect.setVector3(name, this._vectors3[name]);
  46647. }
  46648. // Vector4
  46649. for (name in this._vectors4) {
  46650. this._effect.setVector4(name, this._vectors4[name]);
  46651. }
  46652. // Matrix
  46653. for (name in this._matrices) {
  46654. this._effect.setMatrix(name, this._matrices[name]);
  46655. }
  46656. // Matrix 3x3
  46657. for (name in this._matrices3x3) {
  46658. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46659. }
  46660. // Matrix 2x2
  46661. for (name in this._matrices2x2) {
  46662. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46663. }
  46664. // Vector3Array
  46665. for (name in this._vectors3Arrays) {
  46666. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46667. }
  46668. }
  46669. this._afterBind(mesh);
  46670. };
  46671. ShaderMaterial.prototype.getActiveTextures = function () {
  46672. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46673. for (var name in this._textures) {
  46674. activeTextures.push(this._textures[name]);
  46675. }
  46676. for (var name in this._textureArrays) {
  46677. var array = this._textureArrays[name];
  46678. for (var index = 0; index < array.length; index++) {
  46679. activeTextures.push(array[index]);
  46680. }
  46681. }
  46682. return activeTextures;
  46683. };
  46684. ShaderMaterial.prototype.hasTexture = function (texture) {
  46685. if (_super.prototype.hasTexture.call(this, texture)) {
  46686. return true;
  46687. }
  46688. for (var name in this._textures) {
  46689. if (this._textures[name] === texture) {
  46690. return true;
  46691. }
  46692. }
  46693. for (var name in this._textureArrays) {
  46694. var array = this._textureArrays[name];
  46695. for (var index = 0; index < array.length; index++) {
  46696. if (array[index] === texture) {
  46697. return true;
  46698. }
  46699. }
  46700. }
  46701. return false;
  46702. };
  46703. ShaderMaterial.prototype.clone = function (name) {
  46704. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46705. return newShaderMaterial;
  46706. };
  46707. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46708. if (forceDisposeTextures) {
  46709. var name;
  46710. for (name in this._textures) {
  46711. this._textures[name].dispose();
  46712. }
  46713. for (name in this._textureArrays) {
  46714. var array = this._textureArrays[name];
  46715. for (var index = 0; index < array.length; index++) {
  46716. array[index].dispose();
  46717. }
  46718. }
  46719. }
  46720. this._textures = {};
  46721. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46722. };
  46723. ShaderMaterial.prototype.serialize = function () {
  46724. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46725. serializationObject.customType = "BABYLON.ShaderMaterial";
  46726. serializationObject.options = this._options;
  46727. serializationObject.shaderPath = this._shaderPath;
  46728. var name;
  46729. // Texture
  46730. serializationObject.textures = {};
  46731. for (name in this._textures) {
  46732. serializationObject.textures[name] = this._textures[name].serialize();
  46733. }
  46734. // Texture arrays
  46735. serializationObject.textureArrays = {};
  46736. for (name in this._textureArrays) {
  46737. serializationObject.textureArrays[name] = [];
  46738. var array = this._textureArrays[name];
  46739. for (var index = 0; index < array.length; index++) {
  46740. serializationObject.textureArrays[name].push(array[index].serialize());
  46741. }
  46742. }
  46743. // Float
  46744. serializationObject.floats = {};
  46745. for (name in this._floats) {
  46746. serializationObject.floats[name] = this._floats[name];
  46747. }
  46748. // Float s
  46749. serializationObject.FloatArrays = {};
  46750. for (name in this._floatsArrays) {
  46751. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  46752. }
  46753. // Color3
  46754. serializationObject.colors3 = {};
  46755. for (name in this._colors3) {
  46756. serializationObject.colors3[name] = this._colors3[name].asArray();
  46757. }
  46758. // Color3 array
  46759. serializationObject.colors3Arrays = {};
  46760. for (name in this._colors3Arrays) {
  46761. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  46762. }
  46763. // Color4
  46764. serializationObject.colors4 = {};
  46765. for (name in this._colors4) {
  46766. serializationObject.colors4[name] = this._colors4[name].asArray();
  46767. }
  46768. // Vector2
  46769. serializationObject.vectors2 = {};
  46770. for (name in this._vectors2) {
  46771. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46772. }
  46773. // Vector3
  46774. serializationObject.vectors3 = {};
  46775. for (name in this._vectors3) {
  46776. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46777. }
  46778. // Vector4
  46779. serializationObject.vectors4 = {};
  46780. for (name in this._vectors4) {
  46781. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46782. }
  46783. // Matrix
  46784. serializationObject.matrices = {};
  46785. for (name in this._matrices) {
  46786. serializationObject.matrices[name] = this._matrices[name].asArray();
  46787. }
  46788. // Matrix 3x3
  46789. serializationObject.matrices3x3 = {};
  46790. for (name in this._matrices3x3) {
  46791. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46792. }
  46793. // Matrix 2x2
  46794. serializationObject.matrices2x2 = {};
  46795. for (name in this._matrices2x2) {
  46796. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46797. }
  46798. // Vector3Array
  46799. serializationObject.vectors3Arrays = {};
  46800. for (name in this._vectors3Arrays) {
  46801. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46802. }
  46803. return serializationObject;
  46804. };
  46805. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46806. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46807. var name;
  46808. // Texture
  46809. for (name in source.textures) {
  46810. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46811. }
  46812. // Texture arrays
  46813. for (name in source.textureArrays) {
  46814. var array = source.textureArrays[name];
  46815. var textureArray = new Array();
  46816. for (var index = 0; index < array.length; index++) {
  46817. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46818. }
  46819. material.setTextureArray(name, textureArray);
  46820. }
  46821. // Float
  46822. for (name in source.floats) {
  46823. material.setFloat(name, source.floats[name]);
  46824. }
  46825. // Float s
  46826. for (name in source.floatsArrays) {
  46827. material.setFloats(name, source.floatsArrays[name]);
  46828. }
  46829. // Color3
  46830. for (name in source.colors3) {
  46831. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46832. }
  46833. // Color3 arrays
  46834. for (name in source.colors3Arrays) {
  46835. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  46836. if (i % 3 === 0) {
  46837. arr.push([num]);
  46838. }
  46839. else {
  46840. arr[arr.length - 1].push(num);
  46841. }
  46842. return arr;
  46843. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  46844. material.setColor3Array(name, colors);
  46845. }
  46846. // Color4
  46847. for (name in source.colors4) {
  46848. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46849. }
  46850. // Vector2
  46851. for (name in source.vectors2) {
  46852. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46853. }
  46854. // Vector3
  46855. for (name in source.vectors3) {
  46856. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46857. }
  46858. // Vector4
  46859. for (name in source.vectors4) {
  46860. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46861. }
  46862. // Matrix
  46863. for (name in source.matrices) {
  46864. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46865. }
  46866. // Matrix 3x3
  46867. for (name in source.matrices3x3) {
  46868. material.setMatrix3x3(name, source.matrices3x3[name]);
  46869. }
  46870. // Matrix 2x2
  46871. for (name in source.matrices2x2) {
  46872. material.setMatrix2x2(name, source.matrices2x2[name]);
  46873. }
  46874. // Vector3Array
  46875. for (name in source.vectors3Arrays) {
  46876. material.setArray3(name, source.vectors3Arrays[name]);
  46877. }
  46878. return material;
  46879. };
  46880. return ShaderMaterial;
  46881. }(BABYLON.Material));
  46882. BABYLON.ShaderMaterial = ShaderMaterial;
  46883. })(BABYLON || (BABYLON = {}));
  46884. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46885. var BABYLON;
  46886. (function (BABYLON) {
  46887. var MeshBuilder = /** @class */ (function () {
  46888. function MeshBuilder() {
  46889. }
  46890. MeshBuilder.updateSideOrientation = function (orientation) {
  46891. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  46892. return BABYLON.Mesh.DOUBLESIDE;
  46893. }
  46894. if (orientation === undefined || orientation === null) {
  46895. return BABYLON.Mesh.FRONTSIDE;
  46896. }
  46897. return orientation;
  46898. };
  46899. /**
  46900. * Creates a box mesh.
  46901. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  46902. * The parameter `size` sets the size (float) of each box side (default 1).
  46903. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  46904. * 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).
  46905. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46906. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46907. * 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).
  46908. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46909. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46910. */
  46911. MeshBuilder.CreateBox = function (name, options, scene) {
  46912. if (scene === void 0) { scene = null; }
  46913. var box = new BABYLON.Mesh(name, scene);
  46914. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46915. box._originalBuilderSideOrientation = options.sideOrientation;
  46916. var vertexData = BABYLON.VertexData.CreateBox(options);
  46917. vertexData.applyToMesh(box, options.updatable);
  46918. return box;
  46919. };
  46920. /**
  46921. * Creates a sphere mesh.
  46922. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  46923. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  46924. * 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`).
  46925. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  46926. * 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
  46927. * 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).
  46928. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46929. * 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).
  46930. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46931. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46932. */
  46933. MeshBuilder.CreateSphere = function (name, options, scene) {
  46934. var sphere = new BABYLON.Mesh(name, scene);
  46935. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46936. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46937. var vertexData = BABYLON.VertexData.CreateSphere(options);
  46938. vertexData.applyToMesh(sphere, options.updatable);
  46939. return sphere;
  46940. };
  46941. /**
  46942. * Creates a plane polygonal mesh. By default, this is a disc.
  46943. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  46944. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  46945. * 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.
  46946. * 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
  46947. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46948. * 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).
  46949. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46950. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46951. */
  46952. MeshBuilder.CreateDisc = function (name, options, scene) {
  46953. if (scene === void 0) { scene = null; }
  46954. var disc = new BABYLON.Mesh(name, scene);
  46955. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46956. disc._originalBuilderSideOrientation = options.sideOrientation;
  46957. var vertexData = BABYLON.VertexData.CreateDisc(options);
  46958. vertexData.applyToMesh(disc, options.updatable);
  46959. return disc;
  46960. };
  46961. /**
  46962. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  46963. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  46964. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  46965. * 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`).
  46966. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  46967. * 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.
  46968. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46969. * 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).
  46970. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46971. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46972. */
  46973. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  46974. var sphere = new BABYLON.Mesh(name, scene);
  46975. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46976. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46977. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  46978. vertexData.applyToMesh(sphere, options.updatable);
  46979. return sphere;
  46980. };
  46981. ;
  46982. /**
  46983. * Creates a ribbon mesh.
  46984. * 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.
  46985. *
  46986. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  46987. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  46988. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  46989. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  46990. * 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.
  46991. * 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.
  46992. * 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
  46993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46994. * 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).
  46995. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46996. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46997. * 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.
  46998. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  46999. * 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
  47000. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  47001. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  47002. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47003. */
  47004. MeshBuilder.CreateRibbon = function (name, options, scene) {
  47005. if (scene === void 0) { scene = null; }
  47006. var pathArray = options.pathArray;
  47007. var closeArray = options.closeArray;
  47008. var closePath = options.closePath;
  47009. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47010. var instance = options.instance;
  47011. var updatable = options.updatable;
  47012. if (instance) {
  47013. // positionFunction : ribbon case
  47014. // only pathArray and sideOrientation parameters are taken into account for positions update
  47015. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  47016. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  47017. var positionFunction = function (positions) {
  47018. var minlg = pathArray[0].length;
  47019. var i = 0;
  47020. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  47021. for (var si = 1; si <= ns; si++) {
  47022. for (var p = 0; p < pathArray.length; p++) {
  47023. var path = pathArray[p];
  47024. var l = path.length;
  47025. minlg = (minlg < l) ? minlg : l;
  47026. var j = 0;
  47027. while (j < minlg) {
  47028. positions[i] = path[j].x;
  47029. positions[i + 1] = path[j].y;
  47030. positions[i + 2] = path[j].z;
  47031. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  47032. BABYLON.Tmp.Vector3[0].x = path[j].x;
  47033. }
  47034. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  47035. BABYLON.Tmp.Vector3[1].x = path[j].x;
  47036. }
  47037. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  47038. BABYLON.Tmp.Vector3[0].y = path[j].y;
  47039. }
  47040. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  47041. BABYLON.Tmp.Vector3[1].y = path[j].y;
  47042. }
  47043. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  47044. BABYLON.Tmp.Vector3[0].z = path[j].z;
  47045. }
  47046. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  47047. BABYLON.Tmp.Vector3[1].z = path[j].z;
  47048. }
  47049. j++;
  47050. i += 3;
  47051. }
  47052. if (instance._closePath) {
  47053. positions[i] = path[0].x;
  47054. positions[i + 1] = path[0].y;
  47055. positions[i + 2] = path[0].z;
  47056. i += 3;
  47057. }
  47058. }
  47059. }
  47060. };
  47061. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47062. positionFunction(positions);
  47063. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  47064. instance._boundingInfo.update(instance._worldMatrix);
  47065. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47066. if (options.colors) {
  47067. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47068. for (var c = 0; c < options.colors.length; c++) {
  47069. colors[c * 4] = options.colors[c].r;
  47070. colors[c * 4 + 1] = options.colors[c].g;
  47071. colors[c * 4 + 2] = options.colors[c].b;
  47072. colors[c * 4 + 3] = options.colors[c].a;
  47073. }
  47074. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  47075. }
  47076. if (options.uvs) {
  47077. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47078. for (var i = 0; i < options.uvs.length; i++) {
  47079. uvs[i * 2] = options.uvs[i].x;
  47080. uvs[i * 2 + 1] = options.uvs[i].y;
  47081. }
  47082. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  47083. }
  47084. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  47085. var indices = instance.getIndices();
  47086. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47087. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  47088. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  47089. if (instance._closePath) {
  47090. var indexFirst = 0;
  47091. var indexLast = 0;
  47092. for (var p = 0; p < pathArray.length; p++) {
  47093. indexFirst = instance._idx[p] * 3;
  47094. if (p + 1 < pathArray.length) {
  47095. indexLast = (instance._idx[p + 1] - 1) * 3;
  47096. }
  47097. else {
  47098. indexLast = normals.length - 3;
  47099. }
  47100. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  47101. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  47102. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  47103. normals[indexLast] = normals[indexFirst];
  47104. normals[indexLast + 1] = normals[indexFirst + 1];
  47105. normals[indexLast + 2] = normals[indexFirst + 2];
  47106. }
  47107. }
  47108. if (!(instance.areNormalsFrozen)) {
  47109. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  47110. }
  47111. }
  47112. return instance;
  47113. }
  47114. else {
  47115. var ribbon = new BABYLON.Mesh(name, scene);
  47116. ribbon._originalBuilderSideOrientation = sideOrientation;
  47117. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  47118. if (closePath) {
  47119. ribbon._idx = vertexData._idx;
  47120. }
  47121. ribbon._closePath = closePath;
  47122. ribbon._closeArray = closeArray;
  47123. vertexData.applyToMesh(ribbon, updatable);
  47124. return ribbon;
  47125. }
  47126. };
  47127. /**
  47128. * Creates a cylinder or a cone mesh.
  47129. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  47130. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  47131. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  47132. * 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.
  47133. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  47134. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  47135. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  47136. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  47137. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  47138. * 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).
  47139. * 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
  47140. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  47141. * 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
  47142. * 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.
  47143. * If `enclose` is false, a ring surface is one element.
  47144. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  47145. * 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
  47146. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47147. * 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).
  47148. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47149. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47150. */
  47151. MeshBuilder.CreateCylinder = function (name, options, scene) {
  47152. var cylinder = new BABYLON.Mesh(name, scene);
  47153. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47154. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  47155. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47156. vertexData.applyToMesh(cylinder, options.updatable);
  47157. return cylinder;
  47158. };
  47159. /**
  47160. * Creates a torus mesh.
  47161. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  47162. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47163. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47164. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47165. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47166. * 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).
  47167. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47168. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47169. */
  47170. MeshBuilder.CreateTorus = function (name, options, scene) {
  47171. var torus = new BABYLON.Mesh(name, scene);
  47172. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47173. torus._originalBuilderSideOrientation = options.sideOrientation;
  47174. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47175. vertexData.applyToMesh(torus, options.updatable);
  47176. return torus;
  47177. };
  47178. /**
  47179. * Creates a torus knot mesh.
  47180. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47181. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47182. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47183. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47184. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47185. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47186. * 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).
  47187. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47188. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47189. */
  47190. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47191. var torusKnot = new BABYLON.Mesh(name, scene);
  47192. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47193. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47194. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47195. vertexData.applyToMesh(torusKnot, options.updatable);
  47196. return torusKnot;
  47197. };
  47198. /**
  47199. * Creates a line system mesh.
  47200. * A line system is a pool of many lines gathered in a single mesh.
  47201. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47202. * 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.
  47203. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47204. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47205. * 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
  47206. * 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
  47207. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47209. */
  47210. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47211. var instance = options.instance;
  47212. var lines = options.lines;
  47213. if (instance) {
  47214. var positionFunction = function (positions) {
  47215. var i = 0;
  47216. for (var l = 0; l < lines.length; l++) {
  47217. var points = lines[l];
  47218. for (var p = 0; p < points.length; p++) {
  47219. positions[i] = points[p].x;
  47220. positions[i + 1] = points[p].y;
  47221. positions[i + 2] = points[p].z;
  47222. i += 3;
  47223. }
  47224. }
  47225. };
  47226. instance.updateMeshPositions(positionFunction, false);
  47227. return instance;
  47228. }
  47229. // line system creation
  47230. var lineSystem = new BABYLON.LinesMesh(name, scene);
  47231. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47232. vertexData.applyToMesh(lineSystem, options.updatable);
  47233. return lineSystem;
  47234. };
  47235. /**
  47236. * Creates a line mesh.
  47237. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47238. * 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.
  47239. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47240. * The parameter `points` is an array successive Vector3.
  47241. * 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
  47242. * When updating an instance, remember that only point positions can change, not the number of points.
  47243. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47244. */
  47245. MeshBuilder.CreateLines = function (name, options, scene) {
  47246. if (scene === void 0) { scene = null; }
  47247. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  47248. return lines;
  47249. };
  47250. /**
  47251. * Creates a dashed line mesh.
  47252. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47253. * 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.
  47254. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47255. * The parameter `points` is an array successive Vector3.
  47256. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47257. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47258. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47259. * 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
  47260. * When updating an instance, remember that only point positions can change, not the number of points.
  47261. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47262. */
  47263. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47264. if (scene === void 0) { scene = null; }
  47265. var points = options.points;
  47266. var instance = options.instance;
  47267. var gapSize = options.gapSize || 1;
  47268. var dashSize = options.dashSize || 3;
  47269. if (instance) {
  47270. var positionFunction = function (positions) {
  47271. var curvect = BABYLON.Vector3.Zero();
  47272. var nbSeg = positions.length / 6;
  47273. var lg = 0;
  47274. var nb = 0;
  47275. var shft = 0;
  47276. var dashshft = 0;
  47277. var curshft = 0;
  47278. var p = 0;
  47279. var i = 0;
  47280. var j = 0;
  47281. for (i = 0; i < points.length - 1; i++) {
  47282. points[i + 1].subtractToRef(points[i], curvect);
  47283. lg += curvect.length();
  47284. }
  47285. shft = lg / nbSeg;
  47286. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47287. for (i = 0; i < points.length - 1; i++) {
  47288. points[i + 1].subtractToRef(points[i], curvect);
  47289. nb = Math.floor(curvect.length() / shft);
  47290. curvect.normalize();
  47291. j = 0;
  47292. while (j < nb && p < positions.length) {
  47293. curshft = shft * j;
  47294. positions[p] = points[i].x + curshft * curvect.x;
  47295. positions[p + 1] = points[i].y + curshft * curvect.y;
  47296. positions[p + 2] = points[i].z + curshft * curvect.z;
  47297. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  47298. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  47299. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  47300. p += 6;
  47301. j++;
  47302. }
  47303. }
  47304. while (p < positions.length) {
  47305. positions[p] = points[i].x;
  47306. positions[p + 1] = points[i].y;
  47307. positions[p + 2] = points[i].z;
  47308. p += 3;
  47309. }
  47310. };
  47311. instance.updateMeshPositions(positionFunction, false);
  47312. return instance;
  47313. }
  47314. // dashed lines creation
  47315. var dashedLines = new BABYLON.LinesMesh(name, scene);
  47316. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  47317. vertexData.applyToMesh(dashedLines, options.updatable);
  47318. dashedLines.dashSize = dashSize;
  47319. dashedLines.gapSize = gapSize;
  47320. return dashedLines;
  47321. };
  47322. /**
  47323. * Creates an extruded shape mesh.
  47324. * 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.
  47325. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  47326. *
  47327. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47328. * 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
  47329. * extruded along the Z axis.
  47330. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47331. * 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.
  47332. * The parameter `scale` (float, default 1) is the value to scale the shape.
  47333. * 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
  47334. * 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
  47335. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47336. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47337. * 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).
  47338. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47339. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47341. */
  47342. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  47343. if (scene === void 0) { scene = null; }
  47344. var path = options.path;
  47345. var shape = options.shape;
  47346. var scale = options.scale || 1;
  47347. var rotation = options.rotation || 0;
  47348. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47349. var updatable = options.updatable;
  47350. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47351. var instance = options.instance || null;
  47352. var invertUV = options.invertUV || false;
  47353. 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);
  47354. };
  47355. /**
  47356. * Creates an custom extruded shape mesh.
  47357. * 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.
  47358. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  47359. *
  47360. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47361. * 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
  47362. * extruded along the Z axis.
  47363. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47364. * 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
  47365. * and the distance of this point from the begining of the path :
  47366. * ```javascript
  47367. * var rotationFunction = function(i, distance) {
  47368. * // do things
  47369. * return rotationValue; }
  47370. * ```
  47371. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  47372. * 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
  47373. * and the distance of this point from the begining of the path :
  47374. * ```javascript
  47375. * var scaleFunction = function(i, distance) {
  47376. * // do things
  47377. * return scaleValue;}
  47378. * ```
  47379. * It must returns a float value that will be the scale value applied to the shape on each path point.
  47380. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  47381. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  47382. * 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
  47383. * 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
  47384. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47385. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47386. * 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).
  47387. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47388. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47390. */
  47391. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  47392. var path = options.path;
  47393. var shape = options.shape;
  47394. var scaleFunction = options.scaleFunction || (function () { return 1; });
  47395. var rotationFunction = options.rotationFunction || (function () { return 0; });
  47396. var ribbonCloseArray = options.ribbonCloseArray || false;
  47397. var ribbonClosePath = options.ribbonClosePath || false;
  47398. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47399. var updatable = options.updatable;
  47400. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47401. var instance = options.instance;
  47402. var invertUV = options.invertUV || false;
  47403. 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);
  47404. };
  47405. /**
  47406. * Creates lathe mesh.
  47407. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  47408. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  47409. *
  47410. * 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
  47411. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  47412. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  47413. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  47414. * 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.
  47415. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  47416. * 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
  47417. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47418. * 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).
  47419. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47420. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47421. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47422. */
  47423. MeshBuilder.CreateLathe = function (name, options, scene) {
  47424. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  47425. var closed = (options.closed === undefined) ? true : options.closed;
  47426. var shape = options.shape;
  47427. var radius = options.radius || 1;
  47428. var tessellation = options.tessellation || 64;
  47429. var updatable = options.updatable;
  47430. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47431. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47432. var pi2 = Math.PI * 2;
  47433. var paths = new Array();
  47434. var invertUV = options.invertUV || false;
  47435. var i = 0;
  47436. var p = 0;
  47437. var step = pi2 / tessellation * arc;
  47438. var rotated;
  47439. var path = new Array();
  47440. ;
  47441. for (i = 0; i <= tessellation; i++) {
  47442. var path = [];
  47443. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  47444. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  47445. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  47446. }
  47447. for (p = 0; p < shape.length; p++) {
  47448. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  47449. path.push(rotated);
  47450. }
  47451. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  47452. 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));
  47453. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  47454. }
  47455. paths.push(path);
  47456. }
  47457. // lathe ribbon
  47458. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47459. return lathe;
  47460. };
  47461. /**
  47462. * Creates a plane mesh.
  47463. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47464. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  47465. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  47466. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  47467. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47468. * 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).
  47469. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47470. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47471. */
  47472. MeshBuilder.CreatePlane = function (name, options, scene) {
  47473. var plane = new BABYLON.Mesh(name, scene);
  47474. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47475. plane._originalBuilderSideOrientation = options.sideOrientation;
  47476. var vertexData = BABYLON.VertexData.CreatePlane(options);
  47477. vertexData.applyToMesh(plane, options.updatable);
  47478. if (options.sourcePlane) {
  47479. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  47480. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  47481. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  47482. plane.rotate(vectorProduct, product);
  47483. }
  47484. return plane;
  47485. };
  47486. /**
  47487. * Creates a ground mesh.
  47488. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47489. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  47490. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  47491. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47492. */
  47493. MeshBuilder.CreateGround = function (name, options, scene) {
  47494. var ground = new BABYLON.GroundMesh(name, scene);
  47495. ground._setReady(false);
  47496. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  47497. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  47498. ground._width = options.width || 1;
  47499. ground._height = options.height || 1;
  47500. ground._maxX = ground._width / 2;
  47501. ground._maxZ = ground._height / 2;
  47502. ground._minX = -ground._maxX;
  47503. ground._minZ = -ground._maxZ;
  47504. var vertexData = BABYLON.VertexData.CreateGround(options);
  47505. vertexData.applyToMesh(ground, options.updatable);
  47506. ground._setReady(true);
  47507. return ground;
  47508. };
  47509. /**
  47510. * Creates a tiled ground mesh.
  47511. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  47512. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  47513. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  47514. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  47515. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  47516. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  47517. * numbers of subdivisions on the ground width and height of each tile.
  47518. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47519. */
  47520. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  47521. var tiledGround = new BABYLON.Mesh(name, scene);
  47522. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  47523. vertexData.applyToMesh(tiledGround, options.updatable);
  47524. return tiledGround;
  47525. };
  47526. /**
  47527. * Creates a ground mesh from a height map.
  47528. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  47529. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  47530. * The parameter `url` sets the URL of the height map image resource.
  47531. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  47532. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  47533. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  47534. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  47535. * 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.
  47536. * 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).
  47537. * This function is passed the newly built mesh :
  47538. * ```javascript
  47539. * function(mesh) { // do things
  47540. * return; }
  47541. * ```
  47542. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47543. */
  47544. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  47545. var width = options.width || 10.0;
  47546. var height = options.height || 10.0;
  47547. var subdivisions = options.subdivisions || 1 | 0;
  47548. var minHeight = options.minHeight || 0.0;
  47549. var maxHeight = options.maxHeight || 1.0;
  47550. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  47551. var updatable = options.updatable;
  47552. var onReady = options.onReady;
  47553. var ground = new BABYLON.GroundMesh(name, scene);
  47554. ground._subdivisionsX = subdivisions;
  47555. ground._subdivisionsY = subdivisions;
  47556. ground._width = width;
  47557. ground._height = height;
  47558. ground._maxX = ground._width / 2.0;
  47559. ground._maxZ = ground._height / 2.0;
  47560. ground._minX = -ground._maxX;
  47561. ground._minZ = -ground._maxZ;
  47562. ground._setReady(false);
  47563. var onload = function (img) {
  47564. // Getting height map data
  47565. var canvas = document.createElement("canvas");
  47566. var context = canvas.getContext("2d");
  47567. if (!context) {
  47568. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  47569. }
  47570. var bufferWidth = img.width;
  47571. var bufferHeight = img.height;
  47572. canvas.width = bufferWidth;
  47573. canvas.height = bufferHeight;
  47574. context.drawImage(img, 0, 0);
  47575. // Create VertexData from map data
  47576. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  47577. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  47578. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  47579. width: width, height: height,
  47580. subdivisions: subdivisions,
  47581. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  47582. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  47583. });
  47584. vertexData.applyToMesh(ground, updatable);
  47585. ground._setReady(true);
  47586. //execute ready callback, if set
  47587. if (onReady) {
  47588. onReady(ground);
  47589. }
  47590. };
  47591. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  47592. return ground;
  47593. };
  47594. /**
  47595. * Creates a polygon mesh.
  47596. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  47597. * 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.
  47598. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47599. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47600. * 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).
  47601. * Remember you can only change the shape positions, not their number when updating a polygon.
  47602. */
  47603. MeshBuilder.CreatePolygon = function (name, options, scene) {
  47604. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47605. var shape = options.shape;
  47606. var holes = options.holes || [];
  47607. var depth = options.depth || 0;
  47608. var contours = [];
  47609. var hole = [];
  47610. for (var i = 0; i < shape.length; i++) {
  47611. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  47612. }
  47613. var epsilon = 0.00000001;
  47614. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  47615. contours.pop();
  47616. }
  47617. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  47618. for (var hNb = 0; hNb < holes.length; hNb++) {
  47619. hole = [];
  47620. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  47621. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  47622. }
  47623. polygonTriangulation.addHole(hole);
  47624. }
  47625. var polygon = polygonTriangulation.build(options.updatable, depth);
  47626. polygon._originalBuilderSideOrientation = options.sideOrientation;
  47627. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  47628. vertexData.applyToMesh(polygon, options.updatable);
  47629. return polygon;
  47630. };
  47631. ;
  47632. /**
  47633. * Creates an extruded polygon mesh, with depth in the Y direction.
  47634. * 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).
  47635. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47636. */
  47637. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  47638. return MeshBuilder.CreatePolygon(name, options, scene);
  47639. };
  47640. ;
  47641. /**
  47642. * Creates a tube mesh.
  47643. * 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.
  47644. *
  47645. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  47646. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  47647. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  47648. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  47649. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  47650. * 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.
  47651. * It must return a radius value (positive float) :
  47652. * ```javascript
  47653. * var radiusFunction = function(i, distance) {
  47654. * // do things
  47655. * return radius; }
  47656. * ```
  47657. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  47658. * 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
  47659. * 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
  47660. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47661. * 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).
  47662. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47663. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47664. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47665. */
  47666. MeshBuilder.CreateTube = function (name, options, scene) {
  47667. var path = options.path;
  47668. var instance = options.instance;
  47669. var radius = 1.0;
  47670. if (instance) {
  47671. radius = instance.radius;
  47672. }
  47673. if (options.radius !== undefined) {
  47674. radius = options.radius;
  47675. }
  47676. ;
  47677. var tessellation = options.tessellation || 64 | 0;
  47678. var radiusFunction = options.radiusFunction || null;
  47679. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47680. var invertUV = options.invertUV || false;
  47681. var updatable = options.updatable;
  47682. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47683. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  47684. // tube geometry
  47685. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  47686. var tangents = path3D.getTangents();
  47687. var normals = path3D.getNormals();
  47688. var distances = path3D.getDistances();
  47689. var pi2 = Math.PI * 2;
  47690. var step = pi2 / tessellation * arc;
  47691. var returnRadius = function () { return radius; };
  47692. var radiusFunctionFinal = radiusFunction || returnRadius;
  47693. var circlePath;
  47694. var rad;
  47695. var normal;
  47696. var rotated;
  47697. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47698. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47699. for (var i = 0; i < path.length; i++) {
  47700. rad = radiusFunctionFinal(i, distances[i]); // current radius
  47701. circlePath = Array(); // current circle array
  47702. normal = normals[i]; // current normal
  47703. for (var t = 0; t < tessellation; t++) {
  47704. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  47705. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  47706. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  47707. rotated.scaleInPlace(rad).addInPlace(path[i]);
  47708. circlePath[t] = rotated;
  47709. }
  47710. circlePaths[index] = circlePath;
  47711. index++;
  47712. }
  47713. // cap
  47714. var capPath = function (nbPoints, pathIndex) {
  47715. var pointCap = Array();
  47716. for (var i = 0; i < nbPoints; i++) {
  47717. pointCap.push(path[pathIndex]);
  47718. }
  47719. return pointCap;
  47720. };
  47721. switch (cap) {
  47722. case BABYLON.Mesh.NO_CAP:
  47723. break;
  47724. case BABYLON.Mesh.CAP_START:
  47725. circlePaths[0] = capPath(tessellation, 0);
  47726. circlePaths[1] = circlePaths[2].slice(0);
  47727. break;
  47728. case BABYLON.Mesh.CAP_END:
  47729. circlePaths[index] = circlePaths[index - 1].slice(0);
  47730. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47731. break;
  47732. case BABYLON.Mesh.CAP_ALL:
  47733. circlePaths[0] = capPath(tessellation, 0);
  47734. circlePaths[1] = circlePaths[2].slice(0);
  47735. circlePaths[index] = circlePaths[index - 1].slice(0);
  47736. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47737. break;
  47738. default:
  47739. break;
  47740. }
  47741. return circlePaths;
  47742. };
  47743. var path3D;
  47744. var pathArray;
  47745. if (instance) {
  47746. var arc = options.arc || instance.arc;
  47747. path3D = (instance.path3D).update(path);
  47748. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  47749. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  47750. instance.path3D = path3D;
  47751. instance.pathArray = pathArray;
  47752. instance.arc = arc;
  47753. instance.radius = radius;
  47754. return instance;
  47755. }
  47756. // tube creation
  47757. path3D = new BABYLON.Path3D(path);
  47758. var newPathArray = new Array();
  47759. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47760. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  47761. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47762. tube.pathArray = pathArray;
  47763. tube.path3D = path3D;
  47764. tube.tessellation = tessellation;
  47765. tube.cap = cap;
  47766. tube.arc = options.arc;
  47767. tube.radius = radius;
  47768. return tube;
  47769. };
  47770. /**
  47771. * Creates a polyhedron mesh.
  47772. *
  47773. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  47774. * 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
  47775. * to choose the wanted type.
  47776. * The parameter `size` (positive float, default 1) sets the polygon size.
  47777. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  47778. * 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`.
  47779. * 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
  47780. * 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)`).
  47781. * 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
  47782. * 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.
  47783. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47784. * 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).
  47785. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47786. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47787. */
  47788. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  47789. var polyhedron = new BABYLON.Mesh(name, scene);
  47790. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47791. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  47792. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  47793. vertexData.applyToMesh(polyhedron, options.updatable);
  47794. return polyhedron;
  47795. };
  47796. /**
  47797. * Creates a decal mesh.
  47798. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  47799. * 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.
  47800. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  47801. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  47802. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  47803. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  47804. */
  47805. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  47806. var indices = sourceMesh.getIndices();
  47807. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47808. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47809. var position = options.position || BABYLON.Vector3.Zero();
  47810. var normal = options.normal || BABYLON.Vector3.Up();
  47811. var size = options.size || BABYLON.Vector3.One();
  47812. var angle = options.angle || 0;
  47813. // Getting correct rotation
  47814. if (!normal) {
  47815. var target = new BABYLON.Vector3(0, 0, 1);
  47816. var camera = sourceMesh.getScene().activeCamera;
  47817. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  47818. normal = camera.globalPosition.subtract(cameraWorldTarget);
  47819. }
  47820. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  47821. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  47822. var pitch = Math.atan2(normal.y, len);
  47823. // Matrix
  47824. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  47825. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  47826. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  47827. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  47828. var vertexData = new BABYLON.VertexData();
  47829. vertexData.indices = [];
  47830. vertexData.positions = [];
  47831. vertexData.normals = [];
  47832. vertexData.uvs = [];
  47833. var currentVertexDataIndex = 0;
  47834. var extractDecalVector3 = function (indexId) {
  47835. var result = new BABYLON.PositionNormalVertex();
  47836. if (!indices || !positions || !normals) {
  47837. return result;
  47838. }
  47839. var vertexId = indices[indexId];
  47840. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  47841. // Send vector to decal local world
  47842. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  47843. // Get normal
  47844. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  47845. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  47846. return result;
  47847. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  47848. var clip = function (vertices, axis) {
  47849. if (vertices.length === 0) {
  47850. return vertices;
  47851. }
  47852. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  47853. var clipVertices = function (v0, v1) {
  47854. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  47855. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  47856. };
  47857. var result = new Array();
  47858. for (var index = 0; index < vertices.length; index += 3) {
  47859. var v1Out;
  47860. var v2Out;
  47861. var v3Out;
  47862. var total = 0;
  47863. var nV1 = null;
  47864. var nV2 = null;
  47865. var nV3 = null;
  47866. var nV4 = null;
  47867. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  47868. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  47869. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  47870. v1Out = d1 > 0;
  47871. v2Out = d2 > 0;
  47872. v3Out = d3 > 0;
  47873. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  47874. switch (total) {
  47875. case 0:
  47876. result.push(vertices[index]);
  47877. result.push(vertices[index + 1]);
  47878. result.push(vertices[index + 2]);
  47879. break;
  47880. case 1:
  47881. if (v1Out) {
  47882. nV1 = vertices[index + 1];
  47883. nV2 = vertices[index + 2];
  47884. nV3 = clipVertices(vertices[index], nV1);
  47885. nV4 = clipVertices(vertices[index], nV2);
  47886. }
  47887. if (v2Out) {
  47888. nV1 = vertices[index];
  47889. nV2 = vertices[index + 2];
  47890. nV3 = clipVertices(vertices[index + 1], nV1);
  47891. nV4 = clipVertices(vertices[index + 1], nV2);
  47892. result.push(nV3);
  47893. result.push(nV2.clone());
  47894. result.push(nV1.clone());
  47895. result.push(nV2.clone());
  47896. result.push(nV3.clone());
  47897. result.push(nV4);
  47898. break;
  47899. }
  47900. if (v3Out) {
  47901. nV1 = vertices[index];
  47902. nV2 = vertices[index + 1];
  47903. nV3 = clipVertices(vertices[index + 2], nV1);
  47904. nV4 = clipVertices(vertices[index + 2], nV2);
  47905. }
  47906. if (nV1 && nV2 && nV3 && nV4) {
  47907. result.push(nV1.clone());
  47908. result.push(nV2.clone());
  47909. result.push(nV3);
  47910. result.push(nV4);
  47911. result.push(nV3.clone());
  47912. result.push(nV2.clone());
  47913. }
  47914. break;
  47915. case 2:
  47916. if (!v1Out) {
  47917. nV1 = vertices[index].clone();
  47918. nV2 = clipVertices(nV1, vertices[index + 1]);
  47919. nV3 = clipVertices(nV1, vertices[index + 2]);
  47920. result.push(nV1);
  47921. result.push(nV2);
  47922. result.push(nV3);
  47923. }
  47924. if (!v2Out) {
  47925. nV1 = vertices[index + 1].clone();
  47926. nV2 = clipVertices(nV1, vertices[index + 2]);
  47927. nV3 = clipVertices(nV1, vertices[index]);
  47928. result.push(nV1);
  47929. result.push(nV2);
  47930. result.push(nV3);
  47931. }
  47932. if (!v3Out) {
  47933. nV1 = vertices[index + 2].clone();
  47934. nV2 = clipVertices(nV1, vertices[index]);
  47935. nV3 = clipVertices(nV1, vertices[index + 1]);
  47936. result.push(nV1);
  47937. result.push(nV2);
  47938. result.push(nV3);
  47939. }
  47940. break;
  47941. case 3:
  47942. break;
  47943. }
  47944. }
  47945. return result;
  47946. };
  47947. for (var index = 0; index < indices.length; index += 3) {
  47948. var faceVertices = new Array();
  47949. faceVertices.push(extractDecalVector3(index));
  47950. faceVertices.push(extractDecalVector3(index + 1));
  47951. faceVertices.push(extractDecalVector3(index + 2));
  47952. // Clip
  47953. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  47954. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  47955. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  47956. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  47957. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  47958. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  47959. if (faceVertices.length === 0) {
  47960. continue;
  47961. }
  47962. // Add UVs and get back to world
  47963. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  47964. var vertex = faceVertices[vIndex];
  47965. //TODO check for Int32Array | Uint32Array | Uint16Array
  47966. vertexData.indices.push(currentVertexDataIndex);
  47967. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  47968. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  47969. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  47970. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  47971. currentVertexDataIndex++;
  47972. }
  47973. }
  47974. // Return mesh
  47975. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  47976. vertexData.applyToMesh(decal);
  47977. decal.position = position.clone();
  47978. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  47979. return decal;
  47980. };
  47981. // Privates
  47982. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  47983. // extrusion geometry
  47984. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  47985. var tangents = path3D.getTangents();
  47986. var normals = path3D.getNormals();
  47987. var binormals = path3D.getBinormals();
  47988. var distances = path3D.getDistances();
  47989. var angle = 0;
  47990. var returnScale = function () { return scale !== null ? scale : 1; };
  47991. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  47992. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  47993. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  47994. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47995. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47996. for (var i = 0; i < curve.length; i++) {
  47997. var shapePath = new Array();
  47998. var angleStep = rotate(i, distances[i]);
  47999. var scaleRatio = scl(i, distances[i]);
  48000. for (var p = 0; p < shape.length; p++) {
  48001. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  48002. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  48003. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  48004. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  48005. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  48006. shapePath[p] = rotated;
  48007. }
  48008. shapePaths[index] = shapePath;
  48009. angle += angleStep;
  48010. index++;
  48011. }
  48012. // cap
  48013. var capPath = function (shapePath) {
  48014. var pointCap = Array();
  48015. var barycenter = BABYLON.Vector3.Zero();
  48016. var i;
  48017. for (i = 0; i < shapePath.length; i++) {
  48018. barycenter.addInPlace(shapePath[i]);
  48019. }
  48020. barycenter.scaleInPlace(1.0 / shapePath.length);
  48021. for (i = 0; i < shapePath.length; i++) {
  48022. pointCap.push(barycenter);
  48023. }
  48024. return pointCap;
  48025. };
  48026. switch (cap) {
  48027. case BABYLON.Mesh.NO_CAP:
  48028. break;
  48029. case BABYLON.Mesh.CAP_START:
  48030. shapePaths[0] = capPath(shapePaths[2]);
  48031. shapePaths[1] = shapePaths[2];
  48032. break;
  48033. case BABYLON.Mesh.CAP_END:
  48034. shapePaths[index] = shapePaths[index - 1];
  48035. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48036. break;
  48037. case BABYLON.Mesh.CAP_ALL:
  48038. shapePaths[0] = capPath(shapePaths[2]);
  48039. shapePaths[1] = shapePaths[2];
  48040. shapePaths[index] = shapePaths[index - 1];
  48041. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48042. break;
  48043. default:
  48044. break;
  48045. }
  48046. return shapePaths;
  48047. };
  48048. var path3D;
  48049. var pathArray;
  48050. if (instance) {
  48051. path3D = (instance.path3D).update(curve);
  48052. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  48053. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  48054. return instance;
  48055. }
  48056. // extruded shape creation
  48057. path3D = new BABYLON.Path3D(curve);
  48058. var newShapePaths = new Array();
  48059. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48060. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  48061. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  48062. extrudedGeneric.pathArray = pathArray;
  48063. extrudedGeneric.path3D = path3D;
  48064. extrudedGeneric.cap = cap;
  48065. return extrudedGeneric;
  48066. };
  48067. return MeshBuilder;
  48068. }());
  48069. BABYLON.MeshBuilder = MeshBuilder;
  48070. })(BABYLON || (BABYLON = {}));
  48071. //# sourceMappingURL=babylon.meshBuilder.js.map
  48072. var BABYLON;
  48073. (function (BABYLON) {
  48074. var AudioEngine = /** @class */ (function () {
  48075. function AudioEngine() {
  48076. this._audioContext = null;
  48077. this._audioContextInitialized = false;
  48078. this.canUseWebAudio = false;
  48079. this.WarnedWebAudioUnsupported = false;
  48080. this.unlocked = false;
  48081. this.isMP3supported = false;
  48082. this.isOGGsupported = false;
  48083. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  48084. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  48085. this.canUseWebAudio = true;
  48086. }
  48087. var audioElem = document.createElement('audio');
  48088. try {
  48089. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  48090. this.isMP3supported = true;
  48091. }
  48092. }
  48093. catch (e) {
  48094. // protect error during capability check.
  48095. }
  48096. try {
  48097. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  48098. this.isOGGsupported = true;
  48099. }
  48100. }
  48101. catch (e) {
  48102. // protect error during capability check.
  48103. }
  48104. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  48105. this._unlockiOSaudio();
  48106. }
  48107. else {
  48108. this.unlocked = true;
  48109. }
  48110. }
  48111. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  48112. get: function () {
  48113. if (!this._audioContextInitialized) {
  48114. this._initializeAudioContext();
  48115. }
  48116. return this._audioContext;
  48117. },
  48118. enumerable: true,
  48119. configurable: true
  48120. });
  48121. AudioEngine.prototype._unlockiOSaudio = function () {
  48122. var _this = this;
  48123. var unlockaudio = function () {
  48124. if (!_this.audioContext) {
  48125. return;
  48126. }
  48127. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  48128. var source = _this.audioContext.createBufferSource();
  48129. source.buffer = buffer;
  48130. source.connect(_this.audioContext.destination);
  48131. source.start(0);
  48132. setTimeout(function () {
  48133. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  48134. _this.unlocked = true;
  48135. window.removeEventListener('touchend', unlockaudio, false);
  48136. if (_this.onAudioUnlocked) {
  48137. _this.onAudioUnlocked();
  48138. }
  48139. }
  48140. }, 0);
  48141. };
  48142. window.addEventListener('touchend', unlockaudio, false);
  48143. };
  48144. AudioEngine.prototype._initializeAudioContext = function () {
  48145. try {
  48146. if (this.canUseWebAudio) {
  48147. this._audioContext = new AudioContext();
  48148. // create a global volume gain node
  48149. this.masterGain = this._audioContext.createGain();
  48150. this.masterGain.gain.value = 1;
  48151. this.masterGain.connect(this._audioContext.destination);
  48152. this._audioContextInitialized = true;
  48153. }
  48154. }
  48155. catch (e) {
  48156. this.canUseWebAudio = false;
  48157. BABYLON.Tools.Error("Web Audio: " + e.message);
  48158. }
  48159. };
  48160. AudioEngine.prototype.dispose = function () {
  48161. if (this.canUseWebAudio && this._audioContextInitialized) {
  48162. if (this._connectedAnalyser && this._audioContext) {
  48163. this._connectedAnalyser.stopDebugCanvas();
  48164. this._connectedAnalyser.dispose();
  48165. this.masterGain.disconnect();
  48166. this.masterGain.connect(this._audioContext.destination);
  48167. this._connectedAnalyser = null;
  48168. }
  48169. this.masterGain.gain.value = 1;
  48170. }
  48171. this.WarnedWebAudioUnsupported = false;
  48172. };
  48173. AudioEngine.prototype.getGlobalVolume = function () {
  48174. if (this.canUseWebAudio && this._audioContextInitialized) {
  48175. return this.masterGain.gain.value;
  48176. }
  48177. else {
  48178. return -1;
  48179. }
  48180. };
  48181. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48182. if (this.canUseWebAudio && this._audioContextInitialized) {
  48183. this.masterGain.gain.value = newVolume;
  48184. }
  48185. };
  48186. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48187. if (this._connectedAnalyser) {
  48188. this._connectedAnalyser.stopDebugCanvas();
  48189. }
  48190. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48191. this._connectedAnalyser = analyser;
  48192. this.masterGain.disconnect();
  48193. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48194. }
  48195. };
  48196. return AudioEngine;
  48197. }());
  48198. BABYLON.AudioEngine = AudioEngine;
  48199. })(BABYLON || (BABYLON = {}));
  48200. //# sourceMappingURL=babylon.audioEngine.js.map
  48201. var BABYLON;
  48202. (function (BABYLON) {
  48203. var Sound = /** @class */ (function () {
  48204. /**
  48205. * Create a sound and attach it to a scene
  48206. * @param name Name of your sound
  48207. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48208. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48209. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48210. */
  48211. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48212. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48213. var _this = this;
  48214. this.autoplay = false;
  48215. this.loop = false;
  48216. this.useCustomAttenuation = false;
  48217. this.spatialSound = false;
  48218. this.refDistance = 1;
  48219. this.rolloffFactor = 1;
  48220. this.maxDistance = 100;
  48221. this.distanceModel = "linear";
  48222. this._panningModel = "equalpower";
  48223. this._playbackRate = 1;
  48224. this._streaming = false;
  48225. this._startTime = 0;
  48226. this._startOffset = 0;
  48227. this._position = BABYLON.Vector3.Zero();
  48228. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48229. this._volume = 1;
  48230. this._isLoaded = false;
  48231. this._isReadyToPlay = false;
  48232. this.isPlaying = false;
  48233. this.isPaused = false;
  48234. this._isDirectional = false;
  48235. // Used if you'd like to create a directional sound.
  48236. // If not set, the sound will be omnidirectional
  48237. this._coneInnerAngle = 360;
  48238. this._coneOuterAngle = 360;
  48239. this._coneOuterGain = 0;
  48240. this._isOutputConnected = false;
  48241. this._urlType = "Unknown";
  48242. this.name = name;
  48243. this._scene = scene;
  48244. this._readyToPlayCallback = readyToPlayCallback;
  48245. // Default custom attenuation function is a linear attenuation
  48246. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48247. if (currentDistance < maxDistance) {
  48248. return currentVolume * (1 - currentDistance / maxDistance);
  48249. }
  48250. else {
  48251. return 0;
  48252. }
  48253. };
  48254. if (options) {
  48255. this.autoplay = options.autoplay || false;
  48256. this.loop = options.loop || false;
  48257. // if volume === 0, we need another way to check this option
  48258. if (options.volume !== undefined) {
  48259. this._volume = options.volume;
  48260. }
  48261. this.spatialSound = options.spatialSound || false;
  48262. this.maxDistance = options.maxDistance || 100;
  48263. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48264. this.rolloffFactor = options.rolloffFactor || 1;
  48265. this.refDistance = options.refDistance || 1;
  48266. this.distanceModel = options.distanceModel || "linear";
  48267. this._playbackRate = options.playbackRate || 1;
  48268. this._streaming = options.streaming || false;
  48269. }
  48270. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48271. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48272. this._soundGain.gain.value = this._volume;
  48273. this._inputAudioNode = this._soundGain;
  48274. this._ouputAudioNode = this._soundGain;
  48275. if (this.spatialSound) {
  48276. this._createSpatialParameters();
  48277. }
  48278. this._scene.mainSoundTrack.AddSound(this);
  48279. var validParameter = true;
  48280. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48281. if (urlOrArrayBuffer) {
  48282. if (typeof (urlOrArrayBuffer) === "string")
  48283. this._urlType = "String";
  48284. if (Array.isArray(urlOrArrayBuffer))
  48285. this._urlType = "Array";
  48286. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48287. this._urlType = "ArrayBuffer";
  48288. var urls = [];
  48289. var codecSupportedFound = false;
  48290. switch (this._urlType) {
  48291. case "ArrayBuffer":
  48292. if (urlOrArrayBuffer.byteLength > 0) {
  48293. codecSupportedFound = true;
  48294. this._soundLoaded(urlOrArrayBuffer);
  48295. }
  48296. break;
  48297. case "String":
  48298. urls.push(urlOrArrayBuffer);
  48299. case "Array":
  48300. if (urls.length === 0)
  48301. urls = urlOrArrayBuffer;
  48302. // If we found a supported format, we load it immediately and stop the loop
  48303. for (var i = 0; i < urls.length; i++) {
  48304. var url = urls[i];
  48305. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  48306. codecSupportedFound = true;
  48307. }
  48308. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  48309. codecSupportedFound = true;
  48310. }
  48311. if (url.indexOf(".wav", url.length - 4) !== -1) {
  48312. codecSupportedFound = true;
  48313. }
  48314. if (url.indexOf("blob:") !== -1) {
  48315. codecSupportedFound = true;
  48316. }
  48317. if (codecSupportedFound) {
  48318. // Loading sound using XHR2
  48319. if (!this._streaming) {
  48320. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  48321. }
  48322. else {
  48323. this._htmlAudioElement = new Audio(url);
  48324. this._htmlAudioElement.controls = false;
  48325. this._htmlAudioElement.loop = this.loop;
  48326. this._htmlAudioElement.crossOrigin = "anonymous";
  48327. this._htmlAudioElement.preload = "auto";
  48328. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  48329. _this._isReadyToPlay = true;
  48330. if (_this.autoplay) {
  48331. _this.play();
  48332. }
  48333. if (_this._readyToPlayCallback) {
  48334. _this._readyToPlayCallback();
  48335. }
  48336. });
  48337. document.body.appendChild(this._htmlAudioElement);
  48338. }
  48339. break;
  48340. }
  48341. }
  48342. break;
  48343. default:
  48344. validParameter = false;
  48345. break;
  48346. }
  48347. if (!validParameter) {
  48348. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  48349. }
  48350. else {
  48351. if (!codecSupportedFound) {
  48352. this._isReadyToPlay = true;
  48353. // Simulating a ready to play event to avoid breaking code path
  48354. if (this._readyToPlayCallback) {
  48355. window.setTimeout(function () {
  48356. if (_this._readyToPlayCallback) {
  48357. _this._readyToPlayCallback();
  48358. }
  48359. }, 1000);
  48360. }
  48361. }
  48362. }
  48363. }
  48364. }
  48365. else {
  48366. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  48367. this._scene.mainSoundTrack.AddSound(this);
  48368. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  48369. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  48370. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  48371. }
  48372. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  48373. if (this._readyToPlayCallback) {
  48374. window.setTimeout(function () {
  48375. if (_this._readyToPlayCallback) {
  48376. _this._readyToPlayCallback();
  48377. }
  48378. }, 1000);
  48379. }
  48380. }
  48381. }
  48382. Sound.prototype.dispose = function () {
  48383. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  48384. if (this.isPlaying) {
  48385. this.stop();
  48386. }
  48387. this._isReadyToPlay = false;
  48388. if (this.soundTrackId === -1) {
  48389. this._scene.mainSoundTrack.RemoveSound(this);
  48390. }
  48391. else {
  48392. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  48393. }
  48394. if (this._soundGain) {
  48395. this._soundGain.disconnect();
  48396. this._soundGain = null;
  48397. }
  48398. if (this._soundPanner) {
  48399. this._soundPanner.disconnect();
  48400. this._soundPanner = null;
  48401. }
  48402. if (this._soundSource) {
  48403. this._soundSource.disconnect();
  48404. this._soundSource = null;
  48405. }
  48406. this._audioBuffer = null;
  48407. if (this._htmlAudioElement) {
  48408. this._htmlAudioElement.pause();
  48409. this._htmlAudioElement.src = "";
  48410. document.body.removeChild(this._htmlAudioElement);
  48411. }
  48412. if (this._connectedMesh && this._registerFunc) {
  48413. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48414. this._connectedMesh = null;
  48415. }
  48416. }
  48417. };
  48418. Sound.prototype.isReady = function () {
  48419. return this._isReadyToPlay;
  48420. };
  48421. Sound.prototype._soundLoaded = function (audioData) {
  48422. var _this = this;
  48423. this._isLoaded = true;
  48424. if (!BABYLON.Engine.audioEngine.audioContext) {
  48425. return;
  48426. }
  48427. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  48428. _this._audioBuffer = buffer;
  48429. _this._isReadyToPlay = true;
  48430. if (_this.autoplay) {
  48431. _this.play();
  48432. }
  48433. if (_this._readyToPlayCallback) {
  48434. _this._readyToPlayCallback();
  48435. }
  48436. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  48437. };
  48438. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  48439. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48440. this._audioBuffer = audioBuffer;
  48441. this._isReadyToPlay = true;
  48442. }
  48443. };
  48444. Sound.prototype.updateOptions = function (options) {
  48445. if (options) {
  48446. this.loop = options.loop || this.loop;
  48447. this.maxDistance = options.maxDistance || this.maxDistance;
  48448. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  48449. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  48450. this.refDistance = options.refDistance || this.refDistance;
  48451. this.distanceModel = options.distanceModel || this.distanceModel;
  48452. this._playbackRate = options.playbackRate || this._playbackRate;
  48453. this._updateSpatialParameters();
  48454. if (this.isPlaying) {
  48455. if (this._streaming) {
  48456. this._htmlAudioElement.playbackRate = this._playbackRate;
  48457. }
  48458. else {
  48459. if (this._soundSource) {
  48460. this._soundSource.playbackRate.value = this._playbackRate;
  48461. }
  48462. }
  48463. }
  48464. }
  48465. };
  48466. Sound.prototype._createSpatialParameters = function () {
  48467. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48468. if (this._scene.headphone) {
  48469. this._panningModel = "HRTF";
  48470. }
  48471. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  48472. this._updateSpatialParameters();
  48473. this._soundPanner.connect(this._ouputAudioNode);
  48474. this._inputAudioNode = this._soundPanner;
  48475. }
  48476. };
  48477. Sound.prototype._updateSpatialParameters = function () {
  48478. if (this.spatialSound && this._soundPanner) {
  48479. if (this.useCustomAttenuation) {
  48480. // Tricks to disable in a way embedded Web Audio attenuation
  48481. this._soundPanner.distanceModel = "linear";
  48482. this._soundPanner.maxDistance = Number.MAX_VALUE;
  48483. this._soundPanner.refDistance = 1;
  48484. this._soundPanner.rolloffFactor = 1;
  48485. this._soundPanner.panningModel = this._panningModel;
  48486. }
  48487. else {
  48488. this._soundPanner.distanceModel = this.distanceModel;
  48489. this._soundPanner.maxDistance = this.maxDistance;
  48490. this._soundPanner.refDistance = this.refDistance;
  48491. this._soundPanner.rolloffFactor = this.rolloffFactor;
  48492. this._soundPanner.panningModel = this._panningModel;
  48493. }
  48494. }
  48495. };
  48496. Sound.prototype.switchPanningModelToHRTF = function () {
  48497. this._panningModel = "HRTF";
  48498. this._switchPanningModel();
  48499. };
  48500. Sound.prototype.switchPanningModelToEqualPower = function () {
  48501. this._panningModel = "equalpower";
  48502. this._switchPanningModel();
  48503. };
  48504. Sound.prototype._switchPanningModel = function () {
  48505. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48506. this._soundPanner.panningModel = this._panningModel;
  48507. }
  48508. };
  48509. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  48510. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48511. if (this._isOutputConnected) {
  48512. this._ouputAudioNode.disconnect();
  48513. }
  48514. this._ouputAudioNode.connect(soundTrackAudioNode);
  48515. this._isOutputConnected = true;
  48516. }
  48517. };
  48518. /**
  48519. * Transform this sound into a directional source
  48520. * @param coneInnerAngle Size of the inner cone in degree
  48521. * @param coneOuterAngle Size of the outer cone in degree
  48522. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  48523. */
  48524. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  48525. if (coneOuterAngle < coneInnerAngle) {
  48526. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  48527. return;
  48528. }
  48529. this._coneInnerAngle = coneInnerAngle;
  48530. this._coneOuterAngle = coneOuterAngle;
  48531. this._coneOuterGain = coneOuterGain;
  48532. this._isDirectional = true;
  48533. if (this.isPlaying && this.loop) {
  48534. this.stop();
  48535. this.play();
  48536. }
  48537. };
  48538. Sound.prototype.setPosition = function (newPosition) {
  48539. this._position = newPosition;
  48540. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48541. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48542. }
  48543. };
  48544. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  48545. this._localDirection = newLocalDirection;
  48546. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  48547. this._updateDirection();
  48548. }
  48549. };
  48550. Sound.prototype._updateDirection = function () {
  48551. if (!this._connectedMesh || !this._soundPanner) {
  48552. return;
  48553. }
  48554. var mat = this._connectedMesh.getWorldMatrix();
  48555. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  48556. direction.normalize();
  48557. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  48558. };
  48559. Sound.prototype.updateDistanceFromListener = function () {
  48560. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  48561. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  48562. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  48563. }
  48564. };
  48565. Sound.prototype.setAttenuationFunction = function (callback) {
  48566. this._customAttenuationFunction = callback;
  48567. };
  48568. /**
  48569. * Play the sound
  48570. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  48571. * @param offset (optional) Start the sound setting it at a specific time
  48572. */
  48573. Sound.prototype.play = function (time, offset) {
  48574. var _this = this;
  48575. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  48576. try {
  48577. if (this._startOffset < 0) {
  48578. time = -this._startOffset;
  48579. this._startOffset = 0;
  48580. }
  48581. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48582. if (!this._soundSource || !this._streamingSource) {
  48583. if (this.spatialSound && this._soundPanner) {
  48584. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48585. if (this._isDirectional) {
  48586. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  48587. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  48588. this._soundPanner.coneOuterGain = this._coneOuterGain;
  48589. if (this._connectedMesh) {
  48590. this._updateDirection();
  48591. }
  48592. else {
  48593. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  48594. }
  48595. }
  48596. }
  48597. }
  48598. if (this._streaming) {
  48599. if (!this._streamingSource) {
  48600. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  48601. this._htmlAudioElement.onended = function () { _this._onended(); };
  48602. this._htmlAudioElement.playbackRate = this._playbackRate;
  48603. }
  48604. this._streamingSource.disconnect();
  48605. this._streamingSource.connect(this._inputAudioNode);
  48606. this._htmlAudioElement.play();
  48607. }
  48608. else {
  48609. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  48610. this._soundSource.buffer = this._audioBuffer;
  48611. this._soundSource.connect(this._inputAudioNode);
  48612. this._soundSource.loop = this.loop;
  48613. this._soundSource.playbackRate.value = this._playbackRate;
  48614. this._soundSource.onended = function () { _this._onended(); };
  48615. if (this._soundSource.buffer) {
  48616. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  48617. }
  48618. }
  48619. this._startTime = startTime;
  48620. this.isPlaying = true;
  48621. this.isPaused = false;
  48622. }
  48623. catch (ex) {
  48624. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  48625. }
  48626. }
  48627. };
  48628. Sound.prototype._onended = function () {
  48629. this.isPlaying = false;
  48630. if (this.onended) {
  48631. this.onended();
  48632. }
  48633. };
  48634. /**
  48635. * Stop the sound
  48636. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  48637. */
  48638. Sound.prototype.stop = function (time) {
  48639. if (this.isPlaying) {
  48640. if (this._streaming) {
  48641. this._htmlAudioElement.pause();
  48642. // Test needed for Firefox or it will generate an Invalid State Error
  48643. if (this._htmlAudioElement.currentTime > 0) {
  48644. this._htmlAudioElement.currentTime = 0;
  48645. }
  48646. }
  48647. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  48648. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48649. this._soundSource.stop(stopTime);
  48650. this._soundSource.onended = function () { };
  48651. if (!this.isPaused) {
  48652. this._startOffset = 0;
  48653. }
  48654. }
  48655. this.isPlaying = false;
  48656. }
  48657. };
  48658. Sound.prototype.pause = function () {
  48659. if (this.isPlaying) {
  48660. this.isPaused = true;
  48661. if (this._streaming) {
  48662. this._htmlAudioElement.pause();
  48663. }
  48664. else if (BABYLON.Engine.audioEngine.audioContext) {
  48665. this.stop(0);
  48666. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  48667. }
  48668. }
  48669. };
  48670. Sound.prototype.setVolume = function (newVolume, time) {
  48671. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  48672. if (time && BABYLON.Engine.audioEngine.audioContext) {
  48673. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  48674. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  48675. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  48676. }
  48677. else {
  48678. this._soundGain.gain.value = newVolume;
  48679. }
  48680. }
  48681. this._volume = newVolume;
  48682. };
  48683. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  48684. this._playbackRate = newPlaybackRate;
  48685. if (this.isPlaying) {
  48686. if (this._streaming) {
  48687. this._htmlAudioElement.playbackRate = this._playbackRate;
  48688. }
  48689. else if (this._soundSource) {
  48690. this._soundSource.playbackRate.value = this._playbackRate;
  48691. }
  48692. }
  48693. };
  48694. Sound.prototype.getVolume = function () {
  48695. return this._volume;
  48696. };
  48697. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  48698. var _this = this;
  48699. if (this._connectedMesh && this._registerFunc) {
  48700. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48701. this._registerFunc = null;
  48702. }
  48703. this._connectedMesh = meshToConnectTo;
  48704. if (!this.spatialSound) {
  48705. this.spatialSound = true;
  48706. this._createSpatialParameters();
  48707. if (this.isPlaying && this.loop) {
  48708. this.stop();
  48709. this.play();
  48710. }
  48711. }
  48712. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  48713. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  48714. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  48715. };
  48716. Sound.prototype.detachFromMesh = function () {
  48717. if (this._connectedMesh && this._registerFunc) {
  48718. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48719. this._registerFunc = null;
  48720. this._connectedMesh = null;
  48721. }
  48722. };
  48723. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  48724. var boundingInfo = connectedMesh.getBoundingInfo();
  48725. if (!boundingInfo) {
  48726. return;
  48727. }
  48728. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  48729. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  48730. this._updateDirection();
  48731. }
  48732. };
  48733. Sound.prototype.clone = function () {
  48734. var _this = this;
  48735. if (!this._streaming) {
  48736. var setBufferAndRun = function () {
  48737. if (_this._isReadyToPlay) {
  48738. clonedSound._audioBuffer = _this.getAudioBuffer();
  48739. clonedSound._isReadyToPlay = true;
  48740. if (clonedSound.autoplay) {
  48741. clonedSound.play();
  48742. }
  48743. }
  48744. else {
  48745. window.setTimeout(setBufferAndRun, 300);
  48746. }
  48747. };
  48748. var currentOptions = {
  48749. autoplay: this.autoplay, loop: this.loop,
  48750. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  48751. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  48752. refDistance: this.refDistance, distanceModel: this.distanceModel
  48753. };
  48754. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  48755. if (this.useCustomAttenuation) {
  48756. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  48757. }
  48758. clonedSound.setPosition(this._position);
  48759. clonedSound.setPlaybackRate(this._playbackRate);
  48760. setBufferAndRun();
  48761. return clonedSound;
  48762. }
  48763. else {
  48764. return null;
  48765. }
  48766. };
  48767. Sound.prototype.getAudioBuffer = function () {
  48768. return this._audioBuffer;
  48769. };
  48770. Sound.prototype.serialize = function () {
  48771. var serializationObject = {
  48772. name: this.name,
  48773. url: this.name,
  48774. autoplay: this.autoplay,
  48775. loop: this.loop,
  48776. volume: this._volume,
  48777. spatialSound: this.spatialSound,
  48778. maxDistance: this.maxDistance,
  48779. rolloffFactor: this.rolloffFactor,
  48780. refDistance: this.refDistance,
  48781. distanceModel: this.distanceModel,
  48782. playbackRate: this._playbackRate,
  48783. panningModel: this._panningModel,
  48784. soundTrackId: this.soundTrackId
  48785. };
  48786. if (this.spatialSound) {
  48787. if (this._connectedMesh)
  48788. serializationObject.connectedMeshId = this._connectedMesh.id;
  48789. serializationObject.position = this._position.asArray();
  48790. serializationObject.refDistance = this.refDistance;
  48791. serializationObject.distanceModel = this.distanceModel;
  48792. serializationObject.isDirectional = this._isDirectional;
  48793. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  48794. serializationObject.coneInnerAngle = this._coneInnerAngle;
  48795. serializationObject.coneOuterAngle = this._coneOuterAngle;
  48796. serializationObject.coneOuterGain = this._coneOuterGain;
  48797. }
  48798. return serializationObject;
  48799. };
  48800. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  48801. var soundName = parsedSound.name;
  48802. var soundUrl;
  48803. if (parsedSound.url) {
  48804. soundUrl = rootUrl + parsedSound.url;
  48805. }
  48806. else {
  48807. soundUrl = rootUrl + soundName;
  48808. }
  48809. var options = {
  48810. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  48811. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  48812. rolloffFactor: parsedSound.rolloffFactor,
  48813. refDistance: parsedSound.refDistance,
  48814. distanceModel: parsedSound.distanceModel,
  48815. playbackRate: parsedSound.playbackRate
  48816. };
  48817. var newSound;
  48818. if (!sourceSound) {
  48819. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  48820. scene._addPendingData(newSound);
  48821. }
  48822. else {
  48823. var setBufferAndRun = function () {
  48824. if (sourceSound._isReadyToPlay) {
  48825. newSound._audioBuffer = sourceSound.getAudioBuffer();
  48826. newSound._isReadyToPlay = true;
  48827. if (newSound.autoplay) {
  48828. newSound.play();
  48829. }
  48830. }
  48831. else {
  48832. window.setTimeout(setBufferAndRun, 300);
  48833. }
  48834. };
  48835. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  48836. setBufferAndRun();
  48837. }
  48838. if (parsedSound.position) {
  48839. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  48840. newSound.setPosition(soundPosition);
  48841. }
  48842. if (parsedSound.isDirectional) {
  48843. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  48844. if (parsedSound.localDirectionToMesh) {
  48845. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  48846. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  48847. }
  48848. }
  48849. if (parsedSound.connectedMeshId) {
  48850. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  48851. if (connectedMesh) {
  48852. newSound.attachToMesh(connectedMesh);
  48853. }
  48854. }
  48855. return newSound;
  48856. };
  48857. return Sound;
  48858. }());
  48859. BABYLON.Sound = Sound;
  48860. })(BABYLON || (BABYLON = {}));
  48861. //# sourceMappingURL=babylon.sound.js.map
  48862. var BABYLON;
  48863. (function (BABYLON) {
  48864. var SoundTrack = /** @class */ (function () {
  48865. function SoundTrack(scene, options) {
  48866. this.id = -1;
  48867. this._isMainTrack = false;
  48868. this._isInitialized = false;
  48869. this._scene = scene;
  48870. this.soundCollection = new Array();
  48871. this._options = options;
  48872. if (!this._isMainTrack) {
  48873. this._scene.soundTracks.push(this);
  48874. this.id = this._scene.soundTracks.length - 1;
  48875. }
  48876. }
  48877. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  48878. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48879. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  48880. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  48881. if (this._options) {
  48882. if (this._options.volume) {
  48883. this._outputAudioNode.gain.value = this._options.volume;
  48884. }
  48885. if (this._options.mainTrack) {
  48886. this._isMainTrack = this._options.mainTrack;
  48887. }
  48888. }
  48889. this._isInitialized = true;
  48890. }
  48891. };
  48892. SoundTrack.prototype.dispose = function () {
  48893. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48894. if (this._connectedAnalyser) {
  48895. this._connectedAnalyser.stopDebugCanvas();
  48896. }
  48897. while (this.soundCollection.length) {
  48898. this.soundCollection[0].dispose();
  48899. }
  48900. if (this._outputAudioNode) {
  48901. this._outputAudioNode.disconnect();
  48902. }
  48903. this._outputAudioNode = null;
  48904. }
  48905. };
  48906. SoundTrack.prototype.AddSound = function (sound) {
  48907. if (!this._isInitialized) {
  48908. this._initializeSoundTrackAudioGraph();
  48909. }
  48910. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48911. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  48912. }
  48913. if (sound.soundTrackId) {
  48914. if (sound.soundTrackId === -1) {
  48915. this._scene.mainSoundTrack.RemoveSound(sound);
  48916. }
  48917. else {
  48918. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  48919. }
  48920. }
  48921. this.soundCollection.push(sound);
  48922. sound.soundTrackId = this.id;
  48923. };
  48924. SoundTrack.prototype.RemoveSound = function (sound) {
  48925. var index = this.soundCollection.indexOf(sound);
  48926. if (index !== -1) {
  48927. this.soundCollection.splice(index, 1);
  48928. }
  48929. };
  48930. SoundTrack.prototype.setVolume = function (newVolume) {
  48931. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48932. this._outputAudioNode.gain.value = newVolume;
  48933. }
  48934. };
  48935. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  48936. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48937. for (var i = 0; i < this.soundCollection.length; i++) {
  48938. this.soundCollection[i].switchPanningModelToHRTF();
  48939. }
  48940. }
  48941. };
  48942. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  48943. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48944. for (var i = 0; i < this.soundCollection.length; i++) {
  48945. this.soundCollection[i].switchPanningModelToEqualPower();
  48946. }
  48947. }
  48948. };
  48949. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  48950. if (this._connectedAnalyser) {
  48951. this._connectedAnalyser.stopDebugCanvas();
  48952. }
  48953. this._connectedAnalyser = analyser;
  48954. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48955. this._outputAudioNode.disconnect();
  48956. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  48957. }
  48958. };
  48959. return SoundTrack;
  48960. }());
  48961. BABYLON.SoundTrack = SoundTrack;
  48962. })(BABYLON || (BABYLON = {}));
  48963. //# sourceMappingURL=babylon.soundtrack.js.map
  48964. var BABYLON;
  48965. (function (BABYLON) {
  48966. var Analyser = /** @class */ (function () {
  48967. function Analyser(scene) {
  48968. this.SMOOTHING = 0.75;
  48969. this.FFT_SIZE = 512;
  48970. this.BARGRAPHAMPLITUDE = 256;
  48971. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  48972. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  48973. this._scene = scene;
  48974. this._audioEngine = BABYLON.Engine.audioEngine;
  48975. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  48976. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  48977. this._webAudioAnalyser.minDecibels = -140;
  48978. this._webAudioAnalyser.maxDecibels = 0;
  48979. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48980. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48981. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  48982. }
  48983. }
  48984. Analyser.prototype.getFrequencyBinCount = function () {
  48985. if (this._audioEngine.canUseWebAudio) {
  48986. return this._webAudioAnalyser.frequencyBinCount;
  48987. }
  48988. else {
  48989. return 0;
  48990. }
  48991. };
  48992. Analyser.prototype.getByteFrequencyData = function () {
  48993. if (this._audioEngine.canUseWebAudio) {
  48994. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48995. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48996. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  48997. }
  48998. return this._byteFreqs;
  48999. };
  49000. Analyser.prototype.getByteTimeDomainData = function () {
  49001. if (this._audioEngine.canUseWebAudio) {
  49002. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49003. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49004. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49005. }
  49006. return this._byteTime;
  49007. };
  49008. Analyser.prototype.getFloatFrequencyData = function () {
  49009. if (this._audioEngine.canUseWebAudio) {
  49010. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49011. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49012. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49013. }
  49014. return this._floatFreqs;
  49015. };
  49016. Analyser.prototype.drawDebugCanvas = function () {
  49017. var _this = this;
  49018. if (this._audioEngine.canUseWebAudio) {
  49019. if (!this._debugCanvas) {
  49020. this._debugCanvas = document.createElement("canvas");
  49021. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49022. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49023. this._debugCanvas.style.position = "absolute";
  49024. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49025. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49026. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49027. document.body.appendChild(this._debugCanvas);
  49028. this._registerFunc = function () {
  49029. _this.drawDebugCanvas();
  49030. };
  49031. this._scene.registerBeforeRender(this._registerFunc);
  49032. }
  49033. if (this._registerFunc && this._debugCanvasContext) {
  49034. var workingArray = this.getByteFrequencyData();
  49035. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  49036. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  49037. // Draw the frequency domain chart.
  49038. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  49039. var value = workingArray[i];
  49040. var percent = value / this.BARGRAPHAMPLITUDE;
  49041. var height = this.DEBUGCANVASSIZE.height * percent;
  49042. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  49043. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  49044. var hue = i / this.getFrequencyBinCount() * 360;
  49045. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  49046. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  49047. }
  49048. }
  49049. }
  49050. };
  49051. Analyser.prototype.stopDebugCanvas = function () {
  49052. if (this._debugCanvas) {
  49053. if (this._registerFunc) {
  49054. this._scene.unregisterBeforeRender(this._registerFunc);
  49055. this._registerFunc = null;
  49056. }
  49057. document.body.removeChild(this._debugCanvas);
  49058. this._debugCanvas = null;
  49059. this._debugCanvasContext = null;
  49060. }
  49061. };
  49062. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  49063. if (this._audioEngine.canUseWebAudio) {
  49064. inputAudioNode.connect(this._webAudioAnalyser);
  49065. this._webAudioAnalyser.connect(outputAudioNode);
  49066. }
  49067. };
  49068. Analyser.prototype.dispose = function () {
  49069. if (this._audioEngine.canUseWebAudio) {
  49070. this._webAudioAnalyser.disconnect();
  49071. }
  49072. };
  49073. return Analyser;
  49074. }());
  49075. BABYLON.Analyser = Analyser;
  49076. })(BABYLON || (BABYLON = {}));
  49077. //# sourceMappingURL=babylon.analyser.js.map
  49078. var BABYLON;
  49079. (function (BABYLON) {
  49080. var CubeTexture = /** @class */ (function (_super) {
  49081. __extends(CubeTexture, _super);
  49082. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  49083. if (extensions === void 0) { extensions = null; }
  49084. if (noMipmap === void 0) { noMipmap = false; }
  49085. if (files === void 0) { files = null; }
  49086. if (onLoad === void 0) { onLoad = null; }
  49087. if (onError === void 0) { onError = null; }
  49088. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49089. if (prefiltered === void 0) { prefiltered = false; }
  49090. if (forcedExtension === void 0) { forcedExtension = null; }
  49091. var _this = _super.call(this, scene) || this;
  49092. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49093. _this.name = rootUrl;
  49094. _this.url = rootUrl;
  49095. _this._noMipmap = noMipmap;
  49096. _this.hasAlpha = false;
  49097. _this._format = format;
  49098. _this._prefiltered = prefiltered;
  49099. _this.isCube = true;
  49100. _this._textureMatrix = BABYLON.Matrix.Identity();
  49101. if (prefiltered) {
  49102. _this.gammaSpace = false;
  49103. }
  49104. if (!rootUrl && !files) {
  49105. return _this;
  49106. }
  49107. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  49108. if (!files) {
  49109. if (!extensions) {
  49110. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  49111. }
  49112. files = [];
  49113. for (var index = 0; index < extensions.length; index++) {
  49114. files.push(rootUrl + extensions[index]);
  49115. }
  49116. _this._extensions = extensions;
  49117. }
  49118. _this._files = files;
  49119. if (!_this._texture) {
  49120. if (!scene.useDelayedTextureLoading) {
  49121. if (prefiltered) {
  49122. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  49123. }
  49124. else {
  49125. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  49126. }
  49127. }
  49128. else {
  49129. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49130. }
  49131. }
  49132. else if (onLoad) {
  49133. if (_this._texture.isReady) {
  49134. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  49135. }
  49136. else {
  49137. _this._texture.onLoadedObservable.add(onLoad);
  49138. }
  49139. }
  49140. return _this;
  49141. }
  49142. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  49143. return new CubeTexture("", scene, null, noMipmap, files);
  49144. };
  49145. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  49146. if (forcedExtension === void 0) { forcedExtension = null; }
  49147. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  49148. };
  49149. // Methods
  49150. CubeTexture.prototype.delayLoad = function () {
  49151. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49152. return;
  49153. }
  49154. var scene = this.getScene();
  49155. if (!scene) {
  49156. return;
  49157. }
  49158. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49159. this._texture = this._getFromCache(this.url, this._noMipmap);
  49160. if (!this._texture) {
  49161. if (this._prefiltered) {
  49162. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49163. }
  49164. else {
  49165. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49166. }
  49167. }
  49168. };
  49169. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49170. return this._textureMatrix;
  49171. };
  49172. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49173. this._textureMatrix = value;
  49174. };
  49175. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49176. var texture = BABYLON.SerializationHelper.Parse(function () {
  49177. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49178. }, parsedTexture, scene);
  49179. // Animations
  49180. if (parsedTexture.animations) {
  49181. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49182. var parsedAnimation = parsedTexture.animations[animationIndex];
  49183. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49184. }
  49185. }
  49186. return texture;
  49187. };
  49188. CubeTexture.prototype.clone = function () {
  49189. var _this = this;
  49190. return BABYLON.SerializationHelper.Clone(function () {
  49191. var scene = _this.getScene();
  49192. if (!scene) {
  49193. return _this;
  49194. }
  49195. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49196. }, this);
  49197. };
  49198. return CubeTexture;
  49199. }(BABYLON.BaseTexture));
  49200. BABYLON.CubeTexture = CubeTexture;
  49201. })(BABYLON || (BABYLON = {}));
  49202. //# sourceMappingURL=babylon.cubeTexture.js.map
  49203. var BABYLON;
  49204. (function (BABYLON) {
  49205. var RenderTargetTexture = /** @class */ (function (_super) {
  49206. __extends(RenderTargetTexture, _super);
  49207. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49208. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49209. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49210. if (isCube === void 0) { isCube = false; }
  49211. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49212. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49213. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49214. if (isMulti === void 0) { isMulti = false; }
  49215. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49216. _this.isCube = isCube;
  49217. /**
  49218. * Use this list to define the list of mesh you want to render.
  49219. */
  49220. _this.renderList = new Array();
  49221. _this.renderParticles = true;
  49222. _this.renderSprites = false;
  49223. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49224. _this.ignoreCameraViewport = false;
  49225. // Events
  49226. /**
  49227. * An event triggered when the texture is unbind.
  49228. * @type {BABYLON.Observable}
  49229. */
  49230. _this.onBeforeBindObservable = new BABYLON.Observable();
  49231. /**
  49232. * An event triggered when the texture is unbind.
  49233. * @type {BABYLON.Observable}
  49234. */
  49235. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49236. /**
  49237. * An event triggered before rendering the texture
  49238. * @type {BABYLON.Observable}
  49239. */
  49240. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49241. /**
  49242. * An event triggered after rendering the texture
  49243. * @type {BABYLON.Observable}
  49244. */
  49245. _this.onAfterRenderObservable = new BABYLON.Observable();
  49246. /**
  49247. * An event triggered after the texture clear
  49248. * @type {BABYLON.Observable}
  49249. */
  49250. _this.onClearObservable = new BABYLON.Observable();
  49251. _this._currentRefreshId = -1;
  49252. _this._refreshRate = 1;
  49253. _this._samples = 1;
  49254. scene = _this.getScene();
  49255. if (!scene) {
  49256. return _this;
  49257. }
  49258. _this.name = name;
  49259. _this.isRenderTarget = true;
  49260. _this._size = size;
  49261. _this._generateMipMaps = generateMipMaps ? true : false;
  49262. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49263. // Rendering groups
  49264. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49265. if (isMulti) {
  49266. return _this;
  49267. }
  49268. _this._renderTargetOptions = {
  49269. generateMipMaps: generateMipMaps,
  49270. type: type,
  49271. samplingMode: samplingMode,
  49272. generateDepthBuffer: generateDepthBuffer,
  49273. generateStencilBuffer: generateStencilBuffer
  49274. };
  49275. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49276. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49277. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49278. }
  49279. if (isCube) {
  49280. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  49281. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49282. _this._textureMatrix = BABYLON.Matrix.Identity();
  49283. }
  49284. else {
  49285. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  49286. }
  49287. return _this;
  49288. }
  49289. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  49290. get: function () {
  49291. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  49292. },
  49293. enumerable: true,
  49294. configurable: true
  49295. });
  49296. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  49297. get: function () {
  49298. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  49299. },
  49300. enumerable: true,
  49301. configurable: true
  49302. });
  49303. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  49304. get: function () {
  49305. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  49306. },
  49307. enumerable: true,
  49308. configurable: true
  49309. });
  49310. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  49311. set: function (callback) {
  49312. if (this._onAfterUnbindObserver) {
  49313. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  49314. }
  49315. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  49316. },
  49317. enumerable: true,
  49318. configurable: true
  49319. });
  49320. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  49321. set: function (callback) {
  49322. if (this._onBeforeRenderObserver) {
  49323. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49324. }
  49325. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49326. },
  49327. enumerable: true,
  49328. configurable: true
  49329. });
  49330. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  49331. set: function (callback) {
  49332. if (this._onAfterRenderObserver) {
  49333. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49334. }
  49335. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49336. },
  49337. enumerable: true,
  49338. configurable: true
  49339. });
  49340. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  49341. set: function (callback) {
  49342. if (this._onClearObserver) {
  49343. this.onClearObservable.remove(this._onClearObserver);
  49344. }
  49345. this._onClearObserver = this.onClearObservable.add(callback);
  49346. },
  49347. enumerable: true,
  49348. configurable: true
  49349. });
  49350. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  49351. get: function () {
  49352. return this._renderTargetOptions;
  49353. },
  49354. enumerable: true,
  49355. configurable: true
  49356. });
  49357. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  49358. get: function () {
  49359. return this._samples;
  49360. },
  49361. set: function (value) {
  49362. if (this._samples === value) {
  49363. return;
  49364. }
  49365. var scene = this.getScene();
  49366. if (!scene) {
  49367. return;
  49368. }
  49369. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  49370. },
  49371. enumerable: true,
  49372. configurable: true
  49373. });
  49374. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  49375. this._currentRefreshId = -1;
  49376. };
  49377. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  49378. get: function () {
  49379. return this._refreshRate;
  49380. },
  49381. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49382. set: function (value) {
  49383. this._refreshRate = value;
  49384. this.resetRefreshCounter();
  49385. },
  49386. enumerable: true,
  49387. configurable: true
  49388. });
  49389. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  49390. if (!this._postProcessManager) {
  49391. var scene = this.getScene();
  49392. if (!scene) {
  49393. return;
  49394. }
  49395. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  49396. this._postProcesses = new Array();
  49397. }
  49398. this._postProcesses.push(postProcess);
  49399. this._postProcesses[0].autoClear = false;
  49400. };
  49401. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  49402. if (!this._postProcesses) {
  49403. return;
  49404. }
  49405. if (dispose) {
  49406. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  49407. var postProcess = _a[_i];
  49408. postProcess.dispose();
  49409. }
  49410. }
  49411. this._postProcesses = [];
  49412. };
  49413. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  49414. if (!this._postProcesses) {
  49415. return;
  49416. }
  49417. var index = this._postProcesses.indexOf(postProcess);
  49418. if (index === -1) {
  49419. return;
  49420. }
  49421. this._postProcesses.splice(index, 1);
  49422. if (this._postProcesses.length > 0) {
  49423. this._postProcesses[0].autoClear = false;
  49424. }
  49425. };
  49426. RenderTargetTexture.prototype._shouldRender = function () {
  49427. if (this._currentRefreshId === -1) {
  49428. this._currentRefreshId = 1;
  49429. return true;
  49430. }
  49431. if (this.refreshRate === this._currentRefreshId) {
  49432. this._currentRefreshId = 1;
  49433. return true;
  49434. }
  49435. this._currentRefreshId++;
  49436. return false;
  49437. };
  49438. RenderTargetTexture.prototype.getRenderSize = function () {
  49439. return this._size;
  49440. };
  49441. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  49442. get: function () {
  49443. return true;
  49444. },
  49445. enumerable: true,
  49446. configurable: true
  49447. });
  49448. RenderTargetTexture.prototype.scale = function (ratio) {
  49449. var newSize = this._size * ratio;
  49450. this.resize(newSize);
  49451. };
  49452. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  49453. if (this.isCube) {
  49454. return this._textureMatrix;
  49455. }
  49456. return _super.prototype.getReflectionTextureMatrix.call(this);
  49457. };
  49458. RenderTargetTexture.prototype.resize = function (size) {
  49459. this.releaseInternalTexture();
  49460. var scene = this.getScene();
  49461. if (!scene) {
  49462. return;
  49463. }
  49464. if (this.isCube) {
  49465. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  49466. }
  49467. else {
  49468. this._texture = scene.getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  49469. }
  49470. this._size = size;
  49471. };
  49472. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  49473. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  49474. if (dumpForDebug === void 0) { dumpForDebug = false; }
  49475. var scene = this.getScene();
  49476. if (!scene) {
  49477. return;
  49478. }
  49479. var engine = scene.getEngine();
  49480. if (this.useCameraPostProcesses !== undefined) {
  49481. useCameraPostProcess = this.useCameraPostProcesses;
  49482. }
  49483. if (this._waitingRenderList) {
  49484. this.renderList = [];
  49485. for (var index = 0; index < this._waitingRenderList.length; index++) {
  49486. var id = this._waitingRenderList[index];
  49487. var mesh_1 = scene.getMeshByID(id);
  49488. if (mesh_1) {
  49489. this.renderList.push(mesh_1);
  49490. }
  49491. }
  49492. delete this._waitingRenderList;
  49493. }
  49494. // Is predicate defined?
  49495. if (this.renderListPredicate) {
  49496. if (this.renderList) {
  49497. this.renderList.splice(0); // Clear previous renderList
  49498. }
  49499. else {
  49500. this.renderList = [];
  49501. }
  49502. var scene = this.getScene();
  49503. if (!scene) {
  49504. return;
  49505. }
  49506. var sceneMeshes = scene.meshes;
  49507. for (var index = 0; index < sceneMeshes.length; index++) {
  49508. var mesh = sceneMeshes[index];
  49509. if (this.renderListPredicate(mesh)) {
  49510. this.renderList.push(mesh);
  49511. }
  49512. }
  49513. }
  49514. this.onBeforeBindObservable.notifyObservers(this);
  49515. // Set custom projection.
  49516. // Needs to be before binding to prevent changing the aspect ratio.
  49517. var camera;
  49518. if (this.activeCamera) {
  49519. camera = this.activeCamera;
  49520. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  49521. if (this.activeCamera !== scene.activeCamera) {
  49522. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  49523. }
  49524. }
  49525. else {
  49526. camera = scene.activeCamera;
  49527. if (camera) {
  49528. engine.setViewport(camera.viewport, this._size, this._size);
  49529. }
  49530. }
  49531. // Prepare renderingManager
  49532. this._renderingManager.reset();
  49533. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  49534. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  49535. var sceneRenderId = scene.getRenderId();
  49536. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  49537. var mesh = currentRenderList[meshIndex];
  49538. if (mesh) {
  49539. if (!mesh.isReady()) {
  49540. // Reset _currentRefreshId
  49541. this.resetRefreshCounter();
  49542. continue;
  49543. }
  49544. mesh._preActivateForIntermediateRendering(sceneRenderId);
  49545. var isMasked = void 0;
  49546. if (!this.renderList && camera) {
  49547. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  49548. }
  49549. else {
  49550. isMasked = false;
  49551. }
  49552. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  49553. mesh._activate(sceneRenderId);
  49554. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49555. var subMesh = mesh.subMeshes[subIndex];
  49556. scene._activeIndices.addCount(subMesh.indexCount, false);
  49557. this._renderingManager.dispatch(subMesh);
  49558. }
  49559. }
  49560. }
  49561. }
  49562. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  49563. var particleSystem = scene.particleSystems[particleIndex];
  49564. var emitter = particleSystem.emitter;
  49565. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  49566. continue;
  49567. }
  49568. if (currentRenderList.indexOf(emitter) >= 0) {
  49569. this._renderingManager.dispatchParticles(particleSystem);
  49570. }
  49571. }
  49572. if (this.isCube) {
  49573. for (var face = 0; face < 6; face++) {
  49574. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49575. scene.incrementRenderId();
  49576. scene.resetCachedMaterial();
  49577. }
  49578. }
  49579. else {
  49580. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49581. }
  49582. this.onAfterUnbindObservable.notifyObservers(this);
  49583. if (scene.activeCamera) {
  49584. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  49585. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  49586. }
  49587. engine.setViewport(scene.activeCamera.viewport);
  49588. }
  49589. scene.resetCachedMaterial();
  49590. };
  49591. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  49592. var _this = this;
  49593. var scene = this.getScene();
  49594. if (!scene) {
  49595. return;
  49596. }
  49597. var engine = scene.getEngine();
  49598. if (!this._texture) {
  49599. return;
  49600. }
  49601. // Bind
  49602. if (this._postProcessManager) {
  49603. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  49604. }
  49605. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  49606. if (this._texture) {
  49607. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  49608. }
  49609. }
  49610. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  49611. // Clear
  49612. if (this.onClearObservable.hasObservers()) {
  49613. this.onClearObservable.notifyObservers(engine);
  49614. }
  49615. else {
  49616. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  49617. }
  49618. if (!this._doNotChangeAspectRatio) {
  49619. scene.updateTransformMatrix(true);
  49620. }
  49621. // Render
  49622. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  49623. if (this._postProcessManager) {
  49624. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  49625. }
  49626. else if (useCameraPostProcess) {
  49627. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  49628. }
  49629. if (!this._doNotChangeAspectRatio) {
  49630. scene.updateTransformMatrix(true);
  49631. }
  49632. // Dump ?
  49633. if (dumpForDebug) {
  49634. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  49635. }
  49636. // Unbind
  49637. if (!this.isCube || faceIndex === 5) {
  49638. if (this.isCube) {
  49639. if (faceIndex === 5) {
  49640. engine.generateMipMapsForCubemap(this._texture);
  49641. }
  49642. }
  49643. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  49644. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  49645. });
  49646. }
  49647. else {
  49648. this.onAfterRenderObservable.notifyObservers(faceIndex);
  49649. }
  49650. };
  49651. /**
  49652. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  49653. * This allowed control for front to back rendering or reversly depending of the special needs.
  49654. *
  49655. * @param renderingGroupId The rendering group id corresponding to its index
  49656. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  49657. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  49658. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  49659. */
  49660. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  49661. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  49662. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  49663. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  49664. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  49665. };
  49666. /**
  49667. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  49668. *
  49669. * @param renderingGroupId The rendering group id corresponding to its index
  49670. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  49671. */
  49672. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  49673. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  49674. };
  49675. RenderTargetTexture.prototype.clone = function () {
  49676. var textureSize = this.getSize();
  49677. 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);
  49678. // Base texture
  49679. newTexture.hasAlpha = this.hasAlpha;
  49680. newTexture.level = this.level;
  49681. // RenderTarget Texture
  49682. newTexture.coordinatesMode = this.coordinatesMode;
  49683. if (this.renderList) {
  49684. newTexture.renderList = this.renderList.slice(0);
  49685. }
  49686. return newTexture;
  49687. };
  49688. RenderTargetTexture.prototype.serialize = function () {
  49689. if (!this.name) {
  49690. return null;
  49691. }
  49692. var serializationObject = _super.prototype.serialize.call(this);
  49693. serializationObject.renderTargetSize = this.getRenderSize();
  49694. serializationObject.renderList = [];
  49695. if (this.renderList) {
  49696. for (var index = 0; index < this.renderList.length; index++) {
  49697. serializationObject.renderList.push(this.renderList[index].id);
  49698. }
  49699. }
  49700. return serializationObject;
  49701. };
  49702. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  49703. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  49704. var objBuffer = this.getInternalTexture();
  49705. var scene = this.getScene();
  49706. if (objBuffer && scene) {
  49707. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  49708. }
  49709. };
  49710. RenderTargetTexture.prototype.dispose = function () {
  49711. if (this._postProcessManager) {
  49712. this._postProcessManager.dispose();
  49713. this._postProcessManager = null;
  49714. }
  49715. this.clearPostProcesses(true);
  49716. this.renderList = null;
  49717. // Remove from custom render targets
  49718. var scene = this.getScene();
  49719. if (!scene) {
  49720. return;
  49721. }
  49722. var index = scene.customRenderTargets.indexOf(this);
  49723. if (index >= 0) {
  49724. scene.customRenderTargets.splice(index, 1);
  49725. }
  49726. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  49727. var camera = _a[_i];
  49728. index = camera.customRenderTargets.indexOf(this);
  49729. if (index >= 0) {
  49730. camera.customRenderTargets.splice(index, 1);
  49731. }
  49732. }
  49733. _super.prototype.dispose.call(this);
  49734. };
  49735. RenderTargetTexture.prototype._rebuild = function () {
  49736. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  49737. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  49738. }
  49739. if (this._postProcessManager) {
  49740. this._postProcessManager._rebuild();
  49741. }
  49742. };
  49743. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  49744. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  49745. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  49746. return RenderTargetTexture;
  49747. }(BABYLON.Texture));
  49748. BABYLON.RenderTargetTexture = RenderTargetTexture;
  49749. })(BABYLON || (BABYLON = {}));
  49750. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  49751. var BABYLON;
  49752. (function (BABYLON) {
  49753. ;
  49754. var MultiRenderTarget = /** @class */ (function (_super) {
  49755. __extends(MultiRenderTarget, _super);
  49756. function MultiRenderTarget(name, size, count, scene, options) {
  49757. var _this = this;
  49758. options = options || {};
  49759. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  49760. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  49761. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  49762. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  49763. _this._engine = scene.getEngine();
  49764. if (!_this.isSupported) {
  49765. _this.dispose();
  49766. return;
  49767. }
  49768. var types = [];
  49769. var samplingModes = [];
  49770. for (var i = 0; i < count; i++) {
  49771. if (options.types && options.types[i]) {
  49772. types.push(options.types[i]);
  49773. }
  49774. else {
  49775. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  49776. }
  49777. if (options.samplingModes && options.samplingModes[i]) {
  49778. samplingModes.push(options.samplingModes[i]);
  49779. }
  49780. else {
  49781. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49782. }
  49783. }
  49784. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  49785. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  49786. _this._count = count;
  49787. _this._size = size;
  49788. _this._multiRenderTargetOptions = {
  49789. samplingModes: samplingModes,
  49790. generateMipMaps: generateMipMaps,
  49791. generateDepthBuffer: generateDepthBuffer,
  49792. generateStencilBuffer: generateStencilBuffer,
  49793. generateDepthTexture: generateDepthTexture,
  49794. types: types,
  49795. textureCount: count
  49796. };
  49797. _this._createInternalTextures();
  49798. _this._createTextures();
  49799. return _this;
  49800. }
  49801. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  49802. get: function () {
  49803. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  49804. },
  49805. enumerable: true,
  49806. configurable: true
  49807. });
  49808. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  49809. get: function () {
  49810. return this._textures;
  49811. },
  49812. enumerable: true,
  49813. configurable: true
  49814. });
  49815. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  49816. get: function () {
  49817. return this._textures[this._textures.length - 1];
  49818. },
  49819. enumerable: true,
  49820. configurable: true
  49821. });
  49822. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  49823. set: function (wrap) {
  49824. if (this._textures) {
  49825. for (var i = 0; i < this._textures.length; i++) {
  49826. this._textures[i].wrapU = wrap;
  49827. }
  49828. }
  49829. },
  49830. enumerable: true,
  49831. configurable: true
  49832. });
  49833. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  49834. set: function (wrap) {
  49835. if (this._textures) {
  49836. for (var i = 0; i < this._textures.length; i++) {
  49837. this._textures[i].wrapV = wrap;
  49838. }
  49839. }
  49840. },
  49841. enumerable: true,
  49842. configurable: true
  49843. });
  49844. MultiRenderTarget.prototype._rebuild = function () {
  49845. this.releaseInternalTextures();
  49846. this._createInternalTextures();
  49847. for (var i = 0; i < this._internalTextures.length; i++) {
  49848. var texture = this._textures[i];
  49849. texture._texture = this._internalTextures[i];
  49850. }
  49851. // Keeps references to frame buffer and stencil/depth buffer
  49852. this._texture = this._internalTextures[0];
  49853. };
  49854. MultiRenderTarget.prototype._createInternalTextures = function () {
  49855. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  49856. };
  49857. MultiRenderTarget.prototype._createTextures = function () {
  49858. this._textures = [];
  49859. for (var i = 0; i < this._internalTextures.length; i++) {
  49860. var texture = new BABYLON.Texture(null, this.getScene());
  49861. texture._texture = this._internalTextures[i];
  49862. this._textures.push(texture);
  49863. }
  49864. // Keeps references to frame buffer and stencil/depth buffer
  49865. this._texture = this._internalTextures[0];
  49866. };
  49867. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  49868. get: function () {
  49869. return this._samples;
  49870. },
  49871. set: function (value) {
  49872. if (this._samples === value) {
  49873. return;
  49874. }
  49875. for (var i = 0; i < this._internalTextures.length; i++) {
  49876. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  49877. }
  49878. },
  49879. enumerable: true,
  49880. configurable: true
  49881. });
  49882. MultiRenderTarget.prototype.resize = function (size) {
  49883. this.releaseInternalTextures();
  49884. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  49885. this._createInternalTextures();
  49886. };
  49887. MultiRenderTarget.prototype.dispose = function () {
  49888. this.releaseInternalTextures();
  49889. _super.prototype.dispose.call(this);
  49890. };
  49891. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  49892. if (!this._internalTextures) {
  49893. return;
  49894. }
  49895. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  49896. if (this._internalTextures[i] !== undefined) {
  49897. this._internalTextures[i].dispose();
  49898. this._internalTextures.splice(i, 1);
  49899. }
  49900. }
  49901. };
  49902. return MultiRenderTarget;
  49903. }(BABYLON.RenderTargetTexture));
  49904. BABYLON.MultiRenderTarget = MultiRenderTarget;
  49905. })(BABYLON || (BABYLON = {}));
  49906. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  49907. var BABYLON;
  49908. (function (BABYLON) {
  49909. var MirrorTexture = /** @class */ (function (_super) {
  49910. __extends(MirrorTexture, _super);
  49911. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  49912. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49913. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49914. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49915. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  49916. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  49917. _this._transformMatrix = BABYLON.Matrix.Zero();
  49918. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  49919. _this._blurKernelX = 0;
  49920. _this._blurKernelY = 0;
  49921. _this._blurRatio = 1.0;
  49922. _this.ignoreCameraViewport = true;
  49923. _this.onBeforeRenderObservable.add(function () {
  49924. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  49925. _this._savedViewMatrix = scene.getViewMatrix();
  49926. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  49927. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  49928. scene.clipPlane = _this.mirrorPlane;
  49929. scene.getEngine().cullBackFaces = false;
  49930. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  49931. });
  49932. _this.onAfterRenderObservable.add(function () {
  49933. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  49934. scene.getEngine().cullBackFaces = true;
  49935. scene._mirroredCameraPosition = null;
  49936. delete scene.clipPlane;
  49937. });
  49938. return _this;
  49939. }
  49940. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  49941. get: function () {
  49942. return this._blurRatio;
  49943. },
  49944. set: function (value) {
  49945. if (this._blurRatio === value) {
  49946. return;
  49947. }
  49948. this._blurRatio = value;
  49949. this._preparePostProcesses();
  49950. },
  49951. enumerable: true,
  49952. configurable: true
  49953. });
  49954. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  49955. set: function (value) {
  49956. this.blurKernelX = value;
  49957. this.blurKernelY = value;
  49958. },
  49959. enumerable: true,
  49960. configurable: true
  49961. });
  49962. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  49963. get: function () {
  49964. return this._blurKernelX;
  49965. },
  49966. set: function (value) {
  49967. if (this._blurKernelX === value) {
  49968. return;
  49969. }
  49970. this._blurKernelX = value;
  49971. this._preparePostProcesses();
  49972. },
  49973. enumerable: true,
  49974. configurable: true
  49975. });
  49976. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  49977. get: function () {
  49978. return this._blurKernelY;
  49979. },
  49980. set: function (value) {
  49981. if (this._blurKernelY === value) {
  49982. return;
  49983. }
  49984. this._blurKernelY = value;
  49985. this._preparePostProcesses();
  49986. },
  49987. enumerable: true,
  49988. configurable: true
  49989. });
  49990. MirrorTexture.prototype._preparePostProcesses = function () {
  49991. this.clearPostProcesses(true);
  49992. if (this._blurKernelX && this._blurKernelY) {
  49993. var engine = this.getScene().getEngine();
  49994. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49995. 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);
  49996. this._blurX.autoClear = false;
  49997. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  49998. this._blurX.outputTexture = this._texture;
  49999. }
  50000. else {
  50001. this._blurX.alwaysForcePOT = true;
  50002. }
  50003. 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);
  50004. this._blurY.autoClear = false;
  50005. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  50006. this.addPostProcess(this._blurX);
  50007. this.addPostProcess(this._blurY);
  50008. }
  50009. };
  50010. MirrorTexture.prototype.clone = function () {
  50011. var scene = this.getScene();
  50012. if (!scene) {
  50013. return this;
  50014. }
  50015. var textureSize = this.getSize();
  50016. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  50017. // Base texture
  50018. newTexture.hasAlpha = this.hasAlpha;
  50019. newTexture.level = this.level;
  50020. // Mirror Texture
  50021. newTexture.mirrorPlane = this.mirrorPlane.clone();
  50022. if (this.renderList) {
  50023. newTexture.renderList = this.renderList.slice(0);
  50024. }
  50025. return newTexture;
  50026. };
  50027. MirrorTexture.prototype.serialize = function () {
  50028. if (!this.name) {
  50029. return null;
  50030. }
  50031. var serializationObject = _super.prototype.serialize.call(this);
  50032. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  50033. return serializationObject;
  50034. };
  50035. return MirrorTexture;
  50036. }(BABYLON.RenderTargetTexture));
  50037. BABYLON.MirrorTexture = MirrorTexture;
  50038. })(BABYLON || (BABYLON = {}));
  50039. //# sourceMappingURL=babylon.mirrorTexture.js.map
  50040. var BABYLON;
  50041. (function (BABYLON) {
  50042. /**
  50043. * Creates a refraction texture used by refraction channel of the standard material.
  50044. * @param name the texture name
  50045. * @param size size of the underlying texture
  50046. * @param scene root scene
  50047. */
  50048. var RefractionTexture = /** @class */ (function (_super) {
  50049. __extends(RefractionTexture, _super);
  50050. function RefractionTexture(name, size, scene, generateMipMaps) {
  50051. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  50052. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  50053. _this.depth = 2.0;
  50054. _this.onBeforeRenderObservable.add(function () {
  50055. scene.clipPlane = _this.refractionPlane;
  50056. });
  50057. _this.onAfterRenderObservable.add(function () {
  50058. delete scene.clipPlane;
  50059. });
  50060. return _this;
  50061. }
  50062. RefractionTexture.prototype.clone = function () {
  50063. var scene = this.getScene();
  50064. if (!scene) {
  50065. return this;
  50066. }
  50067. var textureSize = this.getSize();
  50068. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  50069. // Base texture
  50070. newTexture.hasAlpha = this.hasAlpha;
  50071. newTexture.level = this.level;
  50072. // Refraction Texture
  50073. newTexture.refractionPlane = this.refractionPlane.clone();
  50074. if (this.renderList) {
  50075. newTexture.renderList = this.renderList.slice(0);
  50076. }
  50077. newTexture.depth = this.depth;
  50078. return newTexture;
  50079. };
  50080. RefractionTexture.prototype.serialize = function () {
  50081. if (!this.name) {
  50082. return null;
  50083. }
  50084. var serializationObject = _super.prototype.serialize.call(this);
  50085. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  50086. serializationObject.depth = this.depth;
  50087. return serializationObject;
  50088. };
  50089. return RefractionTexture;
  50090. }(BABYLON.RenderTargetTexture));
  50091. BABYLON.RefractionTexture = RefractionTexture;
  50092. })(BABYLON || (BABYLON = {}));
  50093. //# sourceMappingURL=babylon.refractionTexture.js.map
  50094. var BABYLON;
  50095. (function (BABYLON) {
  50096. var DynamicTexture = /** @class */ (function (_super) {
  50097. __extends(DynamicTexture, _super);
  50098. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  50099. if (scene === void 0) { scene = null; }
  50100. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50101. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50102. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  50103. _this.name = name;
  50104. _this._engine = _this.getScene().getEngine();
  50105. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50106. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50107. _this._generateMipMaps = generateMipMaps;
  50108. if (options.getContext) {
  50109. _this._canvas = options;
  50110. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50111. }
  50112. else {
  50113. _this._canvas = document.createElement("canvas");
  50114. if (options.width) {
  50115. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50116. }
  50117. else {
  50118. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  50119. }
  50120. }
  50121. var textureSize = _this.getSize();
  50122. _this._canvas.width = textureSize.width;
  50123. _this._canvas.height = textureSize.height;
  50124. _this._context = _this._canvas.getContext("2d");
  50125. return _this;
  50126. }
  50127. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  50128. get: function () {
  50129. return true;
  50130. },
  50131. enumerable: true,
  50132. configurable: true
  50133. });
  50134. DynamicTexture.prototype._recreate = function (textureSize) {
  50135. this._canvas.width = textureSize.width;
  50136. this._canvas.height = textureSize.height;
  50137. this.releaseInternalTexture();
  50138. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  50139. };
  50140. DynamicTexture.prototype.scale = function (ratio) {
  50141. var textureSize = this.getSize();
  50142. textureSize.width *= ratio;
  50143. textureSize.height *= ratio;
  50144. this._recreate(textureSize);
  50145. };
  50146. DynamicTexture.prototype.scaleTo = function (width, height) {
  50147. var textureSize = this.getSize();
  50148. textureSize.width = width;
  50149. textureSize.height = height;
  50150. this._recreate(textureSize);
  50151. };
  50152. DynamicTexture.prototype.getContext = function () {
  50153. return this._context;
  50154. };
  50155. DynamicTexture.prototype.clear = function () {
  50156. var size = this.getSize();
  50157. this._context.fillRect(0, 0, size.width, size.height);
  50158. };
  50159. DynamicTexture.prototype.update = function (invertY) {
  50160. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  50161. };
  50162. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50163. if (update === void 0) { update = true; }
  50164. var size = this.getSize();
  50165. if (clearColor) {
  50166. this._context.fillStyle = clearColor;
  50167. this._context.fillRect(0, 0, size.width, size.height);
  50168. }
  50169. this._context.font = font;
  50170. if (x === null || x === undefined) {
  50171. var textSize = this._context.measureText(text);
  50172. x = (size.width - textSize.width) / 2;
  50173. }
  50174. if (y === null || y === undefined) {
  50175. var fontSize = parseInt((font.replace(/\D/g, '')));
  50176. ;
  50177. y = (size.height / 2) + (fontSize / 3.65);
  50178. }
  50179. this._context.fillStyle = color;
  50180. this._context.fillText(text, x, y);
  50181. if (update) {
  50182. this.update(invertY);
  50183. }
  50184. };
  50185. DynamicTexture.prototype.clone = function () {
  50186. var scene = this.getScene();
  50187. if (!scene) {
  50188. return this;
  50189. }
  50190. var textureSize = this.getSize();
  50191. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50192. // Base texture
  50193. newTexture.hasAlpha = this.hasAlpha;
  50194. newTexture.level = this.level;
  50195. // Dynamic Texture
  50196. newTexture.wrapU = this.wrapU;
  50197. newTexture.wrapV = this.wrapV;
  50198. return newTexture;
  50199. };
  50200. DynamicTexture.prototype._rebuild = function () {
  50201. this.update();
  50202. };
  50203. return DynamicTexture;
  50204. }(BABYLON.Texture));
  50205. BABYLON.DynamicTexture = DynamicTexture;
  50206. })(BABYLON || (BABYLON = {}));
  50207. //# sourceMappingURL=babylon.dynamicTexture.js.map
  50208. var BABYLON;
  50209. (function (BABYLON) {
  50210. var VideoTexture = /** @class */ (function (_super) {
  50211. __extends(VideoTexture, _super);
  50212. /**
  50213. * Creates a video texture.
  50214. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  50215. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  50216. * @param {BABYLON.Scene} scene is obviously the current scene.
  50217. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  50218. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  50219. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  50220. */
  50221. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  50222. if (generateMipMaps === void 0) { generateMipMaps = false; }
  50223. if (invertY === void 0) { invertY = false; }
  50224. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50225. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50226. _this._autoLaunch = true;
  50227. var urls = null;
  50228. _this.name = name;
  50229. if (urlsOrVideo instanceof HTMLVideoElement) {
  50230. _this.video = urlsOrVideo;
  50231. }
  50232. else {
  50233. urls = urlsOrVideo;
  50234. _this.video = document.createElement("video");
  50235. _this.video.autoplay = false;
  50236. _this.video.loop = true;
  50237. }
  50238. _this._engine = _this.getScene().getEngine();
  50239. _this._generateMipMaps = generateMipMaps;
  50240. _this._samplingMode = samplingMode;
  50241. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  50242. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50243. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50244. }
  50245. else {
  50246. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50247. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50248. _this._generateMipMaps = false;
  50249. }
  50250. if (urls) {
  50251. _this.video.addEventListener("canplay", function () {
  50252. _this._createTexture();
  50253. });
  50254. urls.forEach(function (url) {
  50255. var source = document.createElement("source");
  50256. source.src = url;
  50257. _this.video.appendChild(source);
  50258. });
  50259. }
  50260. else {
  50261. _this._createTexture();
  50262. }
  50263. _this._lastUpdate = BABYLON.Tools.Now;
  50264. return _this;
  50265. }
  50266. VideoTexture.prototype.__setTextureReady = function () {
  50267. if (this._texture) {
  50268. this._texture.isReady = true;
  50269. }
  50270. };
  50271. VideoTexture.prototype._createTexture = function () {
  50272. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  50273. if (this._autoLaunch) {
  50274. this._autoLaunch = false;
  50275. this.video.play();
  50276. }
  50277. this._setTextureReady = this.__setTextureReady.bind(this);
  50278. this.video.addEventListener("playing", this._setTextureReady);
  50279. };
  50280. VideoTexture.prototype._rebuild = function () {
  50281. this.update();
  50282. };
  50283. VideoTexture.prototype.update = function () {
  50284. var now = BABYLON.Tools.Now;
  50285. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  50286. return false;
  50287. }
  50288. this._lastUpdate = now;
  50289. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  50290. return true;
  50291. };
  50292. VideoTexture.prototype.dispose = function () {
  50293. _super.prototype.dispose.call(this);
  50294. this.video.removeEventListener("playing", this._setTextureReady);
  50295. };
  50296. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  50297. var video = document.createElement("video");
  50298. var constraintsDeviceId;
  50299. if (constraints && constraints.deviceId) {
  50300. constraintsDeviceId = {
  50301. exact: constraints.deviceId
  50302. };
  50303. }
  50304. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  50305. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  50306. if (navigator.getUserMedia) {
  50307. navigator.getUserMedia({
  50308. video: {
  50309. deviceId: constraintsDeviceId,
  50310. width: {
  50311. min: (constraints && constraints.minWidth) || 256,
  50312. max: (constraints && constraints.maxWidth) || 640
  50313. },
  50314. height: {
  50315. min: (constraints && constraints.minHeight) || 256,
  50316. max: (constraints && constraints.maxHeight) || 480
  50317. }
  50318. }
  50319. }, function (stream) {
  50320. if (video.mozSrcObject !== undefined) {
  50321. video.mozSrcObject = stream;
  50322. }
  50323. else {
  50324. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  50325. }
  50326. video.play();
  50327. if (onReady) {
  50328. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  50329. }
  50330. }, function (e) {
  50331. BABYLON.Tools.Error(e.name);
  50332. });
  50333. }
  50334. };
  50335. return VideoTexture;
  50336. }(BABYLON.Texture));
  50337. BABYLON.VideoTexture = VideoTexture;
  50338. })(BABYLON || (BABYLON = {}));
  50339. //# sourceMappingURL=babylon.videoTexture.js.map
  50340. var BABYLON;
  50341. (function (BABYLON) {
  50342. var RawTexture = /** @class */ (function (_super) {
  50343. __extends(RawTexture, _super);
  50344. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50345. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50346. if (invertY === void 0) { invertY = false; }
  50347. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50348. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50349. _this.format = format;
  50350. _this._engine = scene.getEngine();
  50351. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50352. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50353. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50354. return _this;
  50355. }
  50356. RawTexture.prototype.update = function (data) {
  50357. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  50358. };
  50359. // Statics
  50360. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50361. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50362. if (invertY === void 0) { invertY = false; }
  50363. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50364. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50365. };
  50366. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50367. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50368. if (invertY === void 0) { invertY = false; }
  50369. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50370. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50371. };
  50372. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50373. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50374. if (invertY === void 0) { invertY = false; }
  50375. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50376. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50377. };
  50378. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50379. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50380. if (invertY === void 0) { invertY = false; }
  50381. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50382. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50383. };
  50384. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50385. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50386. if (invertY === void 0) { invertY = false; }
  50387. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50388. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50389. };
  50390. return RawTexture;
  50391. }(BABYLON.Texture));
  50392. BABYLON.RawTexture = RawTexture;
  50393. })(BABYLON || (BABYLON = {}));
  50394. //# sourceMappingURL=babylon.rawTexture.js.map
  50395. var BABYLON;
  50396. (function (BABYLON) {
  50397. var PostProcess = /** @class */ (function () {
  50398. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  50399. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  50400. if (defines === void 0) { defines = null; }
  50401. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50402. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  50403. if (blockCompilation === void 0) { blockCompilation = false; }
  50404. this.name = name;
  50405. this.width = -1;
  50406. this.height = -1;
  50407. this.autoClear = true;
  50408. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  50409. /*
  50410. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  50411. Can only be used on a single postprocess or on the last one of a chain.
  50412. */
  50413. this.enablePixelPerfectMode = false;
  50414. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  50415. this.alwaysForcePOT = false;
  50416. this.samples = 1;
  50417. this.adaptScaleToCurrentViewport = false;
  50418. this._reusable = false;
  50419. this._textures = new BABYLON.SmartArray(2);
  50420. this._currentRenderTextureInd = 0;
  50421. this._scaleRatio = new BABYLON.Vector2(1, 1);
  50422. this._texelSize = BABYLON.Vector2.Zero();
  50423. // Events
  50424. /**
  50425. * An event triggered when the postprocess is activated.
  50426. * @type {BABYLON.Observable}
  50427. */
  50428. this.onActivateObservable = new BABYLON.Observable();
  50429. /**
  50430. * An event triggered when the postprocess changes its size.
  50431. * @type {BABYLON.Observable}
  50432. */
  50433. this.onSizeChangedObservable = new BABYLON.Observable();
  50434. /**
  50435. * An event triggered when the postprocess applies its effect.
  50436. * @type {BABYLON.Observable}
  50437. */
  50438. this.onApplyObservable = new BABYLON.Observable();
  50439. /**
  50440. * An event triggered before rendering the postprocess
  50441. * @type {BABYLON.Observable}
  50442. */
  50443. this.onBeforeRenderObservable = new BABYLON.Observable();
  50444. /**
  50445. * An event triggered after rendering the postprocess
  50446. * @type {BABYLON.Observable}
  50447. */
  50448. this.onAfterRenderObservable = new BABYLON.Observable();
  50449. if (camera != null) {
  50450. this._camera = camera;
  50451. this._scene = camera.getScene();
  50452. camera.attachPostProcess(this);
  50453. this._engine = this._scene.getEngine();
  50454. this._scene.postProcesses.push(this);
  50455. }
  50456. else if (engine) {
  50457. this._engine = engine;
  50458. this._engine.postProcesses.push(this);
  50459. }
  50460. this._options = options;
  50461. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  50462. this._reusable = reusable || false;
  50463. this._textureType = textureType;
  50464. this._samplers = samplers || [];
  50465. this._samplers.push("textureSampler");
  50466. this._fragmentUrl = fragmentUrl;
  50467. this._vertexUrl = vertexUrl;
  50468. this._parameters = parameters || [];
  50469. this._parameters.push("scale");
  50470. this._indexParameters = indexParameters;
  50471. if (!blockCompilation) {
  50472. this.updateEffect(defines);
  50473. }
  50474. }
  50475. Object.defineProperty(PostProcess.prototype, "onActivate", {
  50476. set: function (callback) {
  50477. if (this._onActivateObserver) {
  50478. this.onActivateObservable.remove(this._onActivateObserver);
  50479. }
  50480. if (callback) {
  50481. this._onActivateObserver = this.onActivateObservable.add(callback);
  50482. }
  50483. },
  50484. enumerable: true,
  50485. configurable: true
  50486. });
  50487. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  50488. set: function (callback) {
  50489. if (this._onSizeChangedObserver) {
  50490. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  50491. }
  50492. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  50493. },
  50494. enumerable: true,
  50495. configurable: true
  50496. });
  50497. Object.defineProperty(PostProcess.prototype, "onApply", {
  50498. set: function (callback) {
  50499. if (this._onApplyObserver) {
  50500. this.onApplyObservable.remove(this._onApplyObserver);
  50501. }
  50502. this._onApplyObserver = this.onApplyObservable.add(callback);
  50503. },
  50504. enumerable: true,
  50505. configurable: true
  50506. });
  50507. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  50508. set: function (callback) {
  50509. if (this._onBeforeRenderObserver) {
  50510. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50511. }
  50512. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50513. },
  50514. enumerable: true,
  50515. configurable: true
  50516. });
  50517. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  50518. set: function (callback) {
  50519. if (this._onAfterRenderObserver) {
  50520. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50521. }
  50522. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50523. },
  50524. enumerable: true,
  50525. configurable: true
  50526. });
  50527. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  50528. get: function () {
  50529. return this._textures.data[this._currentRenderTextureInd];
  50530. },
  50531. set: function (value) {
  50532. this._forcedOutputTexture = value;
  50533. },
  50534. enumerable: true,
  50535. configurable: true
  50536. });
  50537. PostProcess.prototype.getCamera = function () {
  50538. return this._camera;
  50539. };
  50540. Object.defineProperty(PostProcess.prototype, "texelSize", {
  50541. get: function () {
  50542. if (this._shareOutputWithPostProcess) {
  50543. return this._shareOutputWithPostProcess.texelSize;
  50544. }
  50545. if (this._forcedOutputTexture) {
  50546. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  50547. }
  50548. return this._texelSize;
  50549. },
  50550. enumerable: true,
  50551. configurable: true
  50552. });
  50553. PostProcess.prototype.getEngine = function () {
  50554. return this._engine;
  50555. };
  50556. PostProcess.prototype.getEffect = function () {
  50557. return this._effect;
  50558. };
  50559. PostProcess.prototype.shareOutputWith = function (postProcess) {
  50560. this._disposeTextures();
  50561. this._shareOutputWithPostProcess = postProcess;
  50562. return this;
  50563. };
  50564. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  50565. if (defines === void 0) { defines = null; }
  50566. if (uniforms === void 0) { uniforms = null; }
  50567. if (samplers === void 0) { samplers = null; }
  50568. 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);
  50569. };
  50570. PostProcess.prototype.isReusable = function () {
  50571. return this._reusable;
  50572. };
  50573. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  50574. PostProcess.prototype.markTextureDirty = function () {
  50575. this.width = -1;
  50576. };
  50577. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  50578. var _this = this;
  50579. if (sourceTexture === void 0) { sourceTexture = null; }
  50580. camera = camera || this._camera;
  50581. var scene = camera.getScene();
  50582. var engine = scene.getEngine();
  50583. var maxSize = engine.getCaps().maxTextureSize;
  50584. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  50585. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  50586. var desiredWidth = (this._options.width || requiredWidth);
  50587. var desiredHeight = this._options.height || requiredHeight;
  50588. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  50589. if (this.adaptScaleToCurrentViewport) {
  50590. var currentViewport = engine.currentViewport;
  50591. if (currentViewport) {
  50592. desiredWidth *= currentViewport.width;
  50593. desiredHeight *= currentViewport.height;
  50594. }
  50595. }
  50596. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  50597. if (!this._options.width) {
  50598. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  50599. }
  50600. if (!this._options.height) {
  50601. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  50602. }
  50603. }
  50604. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  50605. if (this._textures.length > 0) {
  50606. for (var i = 0; i < this._textures.length; i++) {
  50607. this._engine._releaseTexture(this._textures.data[i]);
  50608. }
  50609. this._textures.reset();
  50610. }
  50611. this.width = desiredWidth;
  50612. this.height = desiredHeight;
  50613. var textureSize = { width: this.width, height: this.height };
  50614. var textureOptions = {
  50615. generateMipMaps: false,
  50616. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  50617. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  50618. samplingMode: this.renderTargetSamplingMode,
  50619. type: this._textureType
  50620. };
  50621. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50622. if (this._reusable) {
  50623. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50624. }
  50625. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  50626. this.onSizeChangedObservable.notifyObservers(this);
  50627. }
  50628. this._textures.forEach(function (texture) {
  50629. if (texture.samples !== _this.samples) {
  50630. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  50631. }
  50632. });
  50633. }
  50634. var target;
  50635. if (this._shareOutputWithPostProcess) {
  50636. target = this._shareOutputWithPostProcess.outputTexture;
  50637. }
  50638. else if (this._forcedOutputTexture) {
  50639. target = this._forcedOutputTexture;
  50640. this.width = this._forcedOutputTexture.width;
  50641. this.height = this._forcedOutputTexture.height;
  50642. }
  50643. else {
  50644. target = this.outputTexture;
  50645. }
  50646. if (this.enablePixelPerfectMode) {
  50647. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  50648. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  50649. }
  50650. else {
  50651. this._scaleRatio.copyFromFloats(1, 1);
  50652. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  50653. }
  50654. this.onActivateObservable.notifyObservers(camera);
  50655. // Clear
  50656. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  50657. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  50658. }
  50659. if (this._reusable) {
  50660. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  50661. }
  50662. };
  50663. Object.defineProperty(PostProcess.prototype, "isSupported", {
  50664. get: function () {
  50665. return this._effect.isSupported;
  50666. },
  50667. enumerable: true,
  50668. configurable: true
  50669. });
  50670. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  50671. get: function () {
  50672. if (this._shareOutputWithPostProcess) {
  50673. return this._shareOutputWithPostProcess.aspectRatio;
  50674. }
  50675. if (this._forcedOutputTexture) {
  50676. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  50677. }
  50678. return this.width / this.height;
  50679. },
  50680. enumerable: true,
  50681. configurable: true
  50682. });
  50683. PostProcess.prototype.apply = function () {
  50684. // Check
  50685. if (!this._effect || !this._effect.isReady())
  50686. return null;
  50687. // States
  50688. this._engine.enableEffect(this._effect);
  50689. this._engine.setState(false);
  50690. this._engine.setDepthBuffer(false);
  50691. this._engine.setDepthWrite(false);
  50692. // Alpha
  50693. this._engine.setAlphaMode(this.alphaMode);
  50694. if (this.alphaConstants) {
  50695. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  50696. }
  50697. // Texture
  50698. var source;
  50699. if (this._shareOutputWithPostProcess) {
  50700. source = this._shareOutputWithPostProcess.outputTexture;
  50701. }
  50702. else if (this._forcedOutputTexture) {
  50703. source = this._forcedOutputTexture;
  50704. }
  50705. else {
  50706. source = this.outputTexture;
  50707. }
  50708. this._effect._bindTexture("textureSampler", source);
  50709. // Parameters
  50710. this._effect.setVector2("scale", this._scaleRatio);
  50711. this.onApplyObservable.notifyObservers(this._effect);
  50712. return this._effect;
  50713. };
  50714. PostProcess.prototype._disposeTextures = function () {
  50715. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  50716. return;
  50717. }
  50718. if (this._textures.length > 0) {
  50719. for (var i = 0; i < this._textures.length; i++) {
  50720. this._engine._releaseTexture(this._textures.data[i]);
  50721. }
  50722. }
  50723. this._textures.dispose();
  50724. };
  50725. PostProcess.prototype.dispose = function (camera) {
  50726. camera = camera || this._camera;
  50727. this._disposeTextures();
  50728. if (this._scene) {
  50729. var index_1 = this._scene.postProcesses.indexOf(this);
  50730. if (index_1 !== -1) {
  50731. this._scene.postProcesses.splice(index_1, 1);
  50732. }
  50733. }
  50734. else {
  50735. var index_2 = this._engine.postProcesses.indexOf(this);
  50736. if (index_2 !== -1) {
  50737. this._engine.postProcesses.splice(index_2, 1);
  50738. }
  50739. }
  50740. if (!camera) {
  50741. return;
  50742. }
  50743. camera.detachPostProcess(this);
  50744. var index = camera._postProcesses.indexOf(this);
  50745. if (index === 0 && camera._postProcesses.length > 0) {
  50746. this._camera._postProcesses[0].markTextureDirty();
  50747. }
  50748. this.onActivateObservable.clear();
  50749. this.onAfterRenderObservable.clear();
  50750. this.onApplyObservable.clear();
  50751. this.onBeforeRenderObservable.clear();
  50752. this.onSizeChangedObservable.clear();
  50753. };
  50754. return PostProcess;
  50755. }());
  50756. BABYLON.PostProcess = PostProcess;
  50757. })(BABYLON || (BABYLON = {}));
  50758. //# sourceMappingURL=babylon.postProcess.js.map
  50759. var BABYLON;
  50760. (function (BABYLON) {
  50761. var PassPostProcess = /** @class */ (function (_super) {
  50762. __extends(PassPostProcess, _super);
  50763. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50764. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50765. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  50766. }
  50767. return PassPostProcess;
  50768. }(BABYLON.PostProcess));
  50769. BABYLON.PassPostProcess = PassPostProcess;
  50770. })(BABYLON || (BABYLON = {}));
  50771. //# sourceMappingURL=babylon.passPostProcess.js.map
  50772. var BABYLON;
  50773. (function (BABYLON) {
  50774. var ShadowGenerator = /** @class */ (function () {
  50775. /**
  50776. * Creates a ShadowGenerator object.
  50777. * A ShadowGenerator is the required tool to use the shadows.
  50778. * Each light casting shadows needs to use its own ShadowGenerator.
  50779. * Required parameters :
  50780. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  50781. * - `light`: the light object generating the shadows.
  50782. * - `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.
  50783. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  50784. */
  50785. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  50786. // Members
  50787. this._bias = 0.00005;
  50788. this._blurBoxOffset = 1;
  50789. this._blurScale = 2;
  50790. this._blurKernel = 1;
  50791. this._useKernelBlur = false;
  50792. this._filter = ShadowGenerator.FILTER_NONE;
  50793. this._darkness = 0;
  50794. this._transparencyShadow = false;
  50795. /**
  50796. * Controls the extent to which the shadows fade out at the edge of the frustum
  50797. * Used only by directionals and spots
  50798. */
  50799. this.frustumEdgeFalloff = 0;
  50800. this.forceBackFacesOnly = false;
  50801. this._lightDirection = BABYLON.Vector3.Zero();
  50802. this._viewMatrix = BABYLON.Matrix.Zero();
  50803. this._projectionMatrix = BABYLON.Matrix.Zero();
  50804. this._transformMatrix = BABYLON.Matrix.Zero();
  50805. this._currentFaceIndex = 0;
  50806. this._currentFaceIndexCache = 0;
  50807. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  50808. this._mapSize = mapSize;
  50809. this._light = light;
  50810. this._scene = light.getScene();
  50811. light._shadowGenerator = this;
  50812. // Texture type fallback from float to int if not supported.
  50813. var caps = this._scene.getEngine().getCaps();
  50814. if (!useFullFloatFirst) {
  50815. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50816. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50817. }
  50818. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50819. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50820. }
  50821. else {
  50822. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50823. }
  50824. }
  50825. else {
  50826. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50827. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50828. }
  50829. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50830. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50831. }
  50832. else {
  50833. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50834. }
  50835. }
  50836. this._initializeGenerator();
  50837. }
  50838. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  50839. // Static
  50840. get: function () {
  50841. return ShadowGenerator._FILTER_NONE;
  50842. },
  50843. enumerable: true,
  50844. configurable: true
  50845. });
  50846. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  50847. get: function () {
  50848. return ShadowGenerator._FILTER_POISSONSAMPLING;
  50849. },
  50850. enumerable: true,
  50851. configurable: true
  50852. });
  50853. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  50854. get: function () {
  50855. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  50856. },
  50857. enumerable: true,
  50858. configurable: true
  50859. });
  50860. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  50861. get: function () {
  50862. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  50863. },
  50864. enumerable: true,
  50865. configurable: true
  50866. });
  50867. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  50868. get: function () {
  50869. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50870. },
  50871. enumerable: true,
  50872. configurable: true
  50873. });
  50874. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  50875. get: function () {
  50876. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50877. },
  50878. enumerable: true,
  50879. configurable: true
  50880. });
  50881. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  50882. get: function () {
  50883. return this._bias;
  50884. },
  50885. set: function (bias) {
  50886. this._bias = bias;
  50887. },
  50888. enumerable: true,
  50889. configurable: true
  50890. });
  50891. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  50892. get: function () {
  50893. return this._blurBoxOffset;
  50894. },
  50895. set: function (value) {
  50896. if (this._blurBoxOffset === value) {
  50897. return;
  50898. }
  50899. this._blurBoxOffset = value;
  50900. this._disposeBlurPostProcesses();
  50901. },
  50902. enumerable: true,
  50903. configurable: true
  50904. });
  50905. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  50906. get: function () {
  50907. return this._blurScale;
  50908. },
  50909. set: function (value) {
  50910. if (this._blurScale === value) {
  50911. return;
  50912. }
  50913. this._blurScale = value;
  50914. this._disposeBlurPostProcesses();
  50915. },
  50916. enumerable: true,
  50917. configurable: true
  50918. });
  50919. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  50920. get: function () {
  50921. return this._blurKernel;
  50922. },
  50923. set: function (value) {
  50924. if (this._blurKernel === value) {
  50925. return;
  50926. }
  50927. this._blurKernel = value;
  50928. this._disposeBlurPostProcesses();
  50929. },
  50930. enumerable: true,
  50931. configurable: true
  50932. });
  50933. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  50934. get: function () {
  50935. return this._useKernelBlur;
  50936. },
  50937. set: function (value) {
  50938. if (this._useKernelBlur === value) {
  50939. return;
  50940. }
  50941. this._useKernelBlur = value;
  50942. this._disposeBlurPostProcesses();
  50943. },
  50944. enumerable: true,
  50945. configurable: true
  50946. });
  50947. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  50948. get: function () {
  50949. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  50950. },
  50951. set: function (value) {
  50952. this._depthScale = value;
  50953. },
  50954. enumerable: true,
  50955. configurable: true
  50956. });
  50957. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  50958. get: function () {
  50959. return this._filter;
  50960. },
  50961. set: function (value) {
  50962. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  50963. if (this._light.needCube()) {
  50964. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50965. this.useExponentialShadowMap = true;
  50966. return;
  50967. }
  50968. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50969. this.useCloseExponentialShadowMap = true;
  50970. return;
  50971. }
  50972. }
  50973. if (this._filter === value) {
  50974. return;
  50975. }
  50976. this._filter = value;
  50977. this._disposeBlurPostProcesses();
  50978. this._applyFilterValues();
  50979. this._light._markMeshesAsLightDirty();
  50980. },
  50981. enumerable: true,
  50982. configurable: true
  50983. });
  50984. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  50985. get: function () {
  50986. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  50987. },
  50988. set: function (value) {
  50989. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  50990. return;
  50991. }
  50992. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  50993. },
  50994. enumerable: true,
  50995. configurable: true
  50996. });
  50997. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  50998. get: function () {
  50999. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51000. return this.useExponentialShadowMap;
  51001. },
  51002. set: function (value) {
  51003. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51004. this.useExponentialShadowMap = value;
  51005. },
  51006. enumerable: true,
  51007. configurable: true
  51008. });
  51009. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  51010. get: function () {
  51011. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51012. return this.useBlurExponentialShadowMap;
  51013. },
  51014. set: function (value) {
  51015. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51016. this.useBlurExponentialShadowMap = value;
  51017. },
  51018. enumerable: true,
  51019. configurable: true
  51020. });
  51021. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  51022. get: function () {
  51023. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  51024. },
  51025. set: function (value) {
  51026. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  51027. return;
  51028. }
  51029. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51030. },
  51031. enumerable: true,
  51032. configurable: true
  51033. });
  51034. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  51035. get: function () {
  51036. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  51037. },
  51038. set: function (value) {
  51039. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51040. return;
  51041. }
  51042. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51043. },
  51044. enumerable: true,
  51045. configurable: true
  51046. });
  51047. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  51048. get: function () {
  51049. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51050. },
  51051. set: function (value) {
  51052. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  51053. return;
  51054. }
  51055. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51056. },
  51057. enumerable: true,
  51058. configurable: true
  51059. });
  51060. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  51061. get: function () {
  51062. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51063. },
  51064. set: function (value) {
  51065. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51066. return;
  51067. }
  51068. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51069. },
  51070. enumerable: true,
  51071. configurable: true
  51072. });
  51073. /**
  51074. * Returns the darkness value (float).
  51075. */
  51076. ShadowGenerator.prototype.getDarkness = function () {
  51077. return this._darkness;
  51078. };
  51079. /**
  51080. * Sets the ShadowGenerator darkness value (float <= 1.0).
  51081. * Returns the ShadowGenerator.
  51082. */
  51083. ShadowGenerator.prototype.setDarkness = function (darkness) {
  51084. if (darkness >= 1.0)
  51085. this._darkness = 1.0;
  51086. else if (darkness <= 0.0)
  51087. this._darkness = 0.0;
  51088. else
  51089. this._darkness = darkness;
  51090. return this;
  51091. };
  51092. /**
  51093. * Sets the ability to have transparent shadow (boolean).
  51094. * Returns the ShadowGenerator.
  51095. */
  51096. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  51097. this._transparencyShadow = hasShadow;
  51098. return this;
  51099. };
  51100. /**
  51101. * Returns a RenderTargetTexture object : the shadow map texture.
  51102. */
  51103. ShadowGenerator.prototype.getShadowMap = function () {
  51104. return this._shadowMap;
  51105. };
  51106. /**
  51107. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  51108. */
  51109. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  51110. if (this._shadowMap2) {
  51111. return this._shadowMap2;
  51112. }
  51113. return this._shadowMap;
  51114. };
  51115. /**
  51116. * Helper function to add a mesh and its descendants to the list of shadow casters
  51117. * @param mesh Mesh to add
  51118. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  51119. */
  51120. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  51121. if (includeDescendants === void 0) { includeDescendants = true; }
  51122. if (!this._shadowMap) {
  51123. return this;
  51124. }
  51125. if (!this._shadowMap.renderList) {
  51126. this._shadowMap.renderList = [];
  51127. }
  51128. this._shadowMap.renderList.push(mesh);
  51129. if (includeDescendants) {
  51130. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  51131. }
  51132. return this;
  51133. var _a;
  51134. };
  51135. /**
  51136. * Helper function to remove a mesh and its descendants from the list of shadow casters
  51137. * @param mesh Mesh to remove
  51138. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  51139. */
  51140. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  51141. if (includeDescendants === void 0) { includeDescendants = true; }
  51142. if (!this._shadowMap || !this._shadowMap.renderList) {
  51143. return this;
  51144. }
  51145. var index = this._shadowMap.renderList.indexOf(mesh);
  51146. if (index !== -1) {
  51147. this._shadowMap.renderList.splice(index, 1);
  51148. }
  51149. if (includeDescendants) {
  51150. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  51151. var child = _a[_i];
  51152. this.removeShadowCaster(child);
  51153. }
  51154. }
  51155. return this;
  51156. };
  51157. /**
  51158. * Returns the associated light object.
  51159. */
  51160. ShadowGenerator.prototype.getLight = function () {
  51161. return this._light;
  51162. };
  51163. ShadowGenerator.prototype._initializeGenerator = function () {
  51164. this._light._markMeshesAsLightDirty();
  51165. this._initializeShadowMap();
  51166. };
  51167. ShadowGenerator.prototype._initializeShadowMap = function () {
  51168. var _this = this;
  51169. // Render target
  51170. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51171. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51172. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51173. this._shadowMap.anisotropicFilteringLevel = 1;
  51174. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51175. this._shadowMap.renderParticles = false;
  51176. this._shadowMap.ignoreCameraViewport = true;
  51177. // Record Face Index before render.
  51178. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51179. _this._currentFaceIndex = faceIndex;
  51180. });
  51181. // Custom render function.
  51182. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51183. // Blur if required afer render.
  51184. this._shadowMap.onAfterUnbindObservable.add(function () {
  51185. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51186. return;
  51187. }
  51188. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51189. _this._initializeBlurRTTAndPostProcesses();
  51190. }
  51191. var shadowMap = _this.getShadowMapForRendering();
  51192. if (shadowMap) {
  51193. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  51194. }
  51195. });
  51196. // Clear according to the chosen filter.
  51197. this._shadowMap.onClearObservable.add(function (engine) {
  51198. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  51199. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  51200. }
  51201. else {
  51202. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51203. }
  51204. });
  51205. };
  51206. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  51207. var _this = this;
  51208. var engine = this._scene.getEngine();
  51209. var targetSize = this._mapSize / this.blurScale;
  51210. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  51211. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  51212. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51213. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51214. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51215. }
  51216. if (this.useKernelBlur) {
  51217. 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);
  51218. this._kernelBlurXPostprocess.width = targetSize;
  51219. this._kernelBlurXPostprocess.height = targetSize;
  51220. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  51221. effect.setTexture("textureSampler", _this._shadowMap);
  51222. });
  51223. 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);
  51224. this._kernelBlurXPostprocess.autoClear = false;
  51225. this._kernelBlurYPostprocess.autoClear = false;
  51226. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51227. this._kernelBlurXPostprocess.packedFloat = true;
  51228. this._kernelBlurYPostprocess.packedFloat = true;
  51229. }
  51230. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  51231. }
  51232. else {
  51233. 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);
  51234. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  51235. effect.setFloat2("screenSize", targetSize, targetSize);
  51236. effect.setTexture("textureSampler", _this._shadowMap);
  51237. });
  51238. this._boxBlurPostprocess.autoClear = false;
  51239. this._blurPostProcesses = [this._boxBlurPostprocess];
  51240. }
  51241. };
  51242. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  51243. var index;
  51244. var engine = this._scene.getEngine();
  51245. if (depthOnlySubMeshes.length) {
  51246. engine.setColorWrite(false);
  51247. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  51248. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  51249. }
  51250. engine.setColorWrite(true);
  51251. }
  51252. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51253. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  51254. }
  51255. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51256. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  51257. }
  51258. if (this._transparencyShadow) {
  51259. for (index = 0; index < transparentSubMeshes.length; index++) {
  51260. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  51261. }
  51262. }
  51263. };
  51264. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  51265. var _this = this;
  51266. var mesh = subMesh.getRenderingMesh();
  51267. var scene = this._scene;
  51268. var engine = scene.getEngine();
  51269. var material = subMesh.getMaterial();
  51270. if (!material) {
  51271. return;
  51272. }
  51273. // Culling
  51274. engine.setState(material.backFaceCulling);
  51275. // Managing instances
  51276. var batch = mesh._getInstancesRenderList(subMesh._id);
  51277. if (batch.mustReturn) {
  51278. return;
  51279. }
  51280. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  51281. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  51282. engine.enableEffect(this._effect);
  51283. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  51284. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  51285. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  51286. this._effect.setVector3("lightPosition", this.getLight().position);
  51287. if (scene.activeCamera) {
  51288. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  51289. }
  51290. // Alpha test
  51291. if (material && material.needAlphaTesting()) {
  51292. var alphaTexture = material.getAlphaTestTexture();
  51293. if (alphaTexture) {
  51294. this._effect.setTexture("diffuseSampler", alphaTexture);
  51295. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  51296. }
  51297. }
  51298. // Bones
  51299. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51300. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  51301. }
  51302. if (this.forceBackFacesOnly) {
  51303. engine.setState(true, 0, false, true);
  51304. }
  51305. // Draw
  51306. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51307. if (this.forceBackFacesOnly) {
  51308. engine.setState(true, 0, false, false);
  51309. }
  51310. }
  51311. else {
  51312. // Need to reset refresh rate of the shadowMap
  51313. if (this._shadowMap) {
  51314. this._shadowMap.resetRefreshCounter();
  51315. }
  51316. }
  51317. };
  51318. ShadowGenerator.prototype._applyFilterValues = function () {
  51319. if (!this._shadowMap) {
  51320. return;
  51321. }
  51322. if (this.filter === ShadowGenerator.FILTER_NONE) {
  51323. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  51324. }
  51325. else {
  51326. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51327. }
  51328. };
  51329. /**
  51330. * Force shader compilation including textures ready check
  51331. */
  51332. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  51333. var _this = this;
  51334. var shadowMap = this.getShadowMap();
  51335. if (!shadowMap) {
  51336. return;
  51337. }
  51338. var subMeshes = new Array();
  51339. var currentIndex = 0;
  51340. var renderList = shadowMap.renderList;
  51341. if (!renderList) {
  51342. return;
  51343. }
  51344. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  51345. var mesh = renderList_1[_i];
  51346. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  51347. }
  51348. var checkReady = function () {
  51349. if (!_this._scene || !_this._scene.getEngine()) {
  51350. return;
  51351. }
  51352. var subMesh = subMeshes[currentIndex];
  51353. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  51354. currentIndex++;
  51355. if (currentIndex >= subMeshes.length) {
  51356. if (onCompiled) {
  51357. onCompiled(_this);
  51358. }
  51359. return;
  51360. }
  51361. }
  51362. setTimeout(checkReady, 16);
  51363. };
  51364. if (subMeshes.length > 0) {
  51365. checkReady();
  51366. }
  51367. };
  51368. /**
  51369. * Boolean : true when the ShadowGenerator is finally computed.
  51370. */
  51371. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  51372. var defines = [];
  51373. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51374. defines.push("#define FLOAT");
  51375. }
  51376. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51377. defines.push("#define ESM");
  51378. }
  51379. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51380. var mesh = subMesh.getMesh();
  51381. var material = subMesh.getMaterial();
  51382. // Alpha test
  51383. if (material && material.needAlphaTesting()) {
  51384. var alphaTexture = material.getAlphaTestTexture();
  51385. if (alphaTexture) {
  51386. defines.push("#define ALPHATEST");
  51387. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51388. attribs.push(BABYLON.VertexBuffer.UVKind);
  51389. defines.push("#define UV1");
  51390. }
  51391. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51392. if (alphaTexture.coordinatesIndex === 1) {
  51393. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51394. defines.push("#define UV2");
  51395. }
  51396. }
  51397. }
  51398. }
  51399. // Bones
  51400. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51401. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51402. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51403. if (mesh.numBoneInfluencers > 4) {
  51404. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51405. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51406. }
  51407. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51408. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51409. }
  51410. else {
  51411. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51412. }
  51413. // Instances
  51414. if (useInstances) {
  51415. defines.push("#define INSTANCES");
  51416. attribs.push("world0");
  51417. attribs.push("world1");
  51418. attribs.push("world2");
  51419. attribs.push("world3");
  51420. }
  51421. // Get correct effect
  51422. var join = defines.join("\n");
  51423. if (this._cachedDefines !== join) {
  51424. this._cachedDefines = join;
  51425. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  51426. }
  51427. return this._effect.isReady();
  51428. };
  51429. /**
  51430. * This creates the defines related to the standard BJS materials.
  51431. */
  51432. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  51433. var scene = this._scene;
  51434. var light = this._light;
  51435. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51436. return;
  51437. }
  51438. defines["SHADOW" + lightIndex] = true;
  51439. if (this.usePoissonSampling) {
  51440. defines["SHADOWPCF" + lightIndex] = true;
  51441. }
  51442. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51443. defines["SHADOWESM" + lightIndex] = true;
  51444. }
  51445. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  51446. defines["SHADOWCLOSEESM" + lightIndex] = true;
  51447. }
  51448. if (light.needCube()) {
  51449. defines["SHADOWCUBE" + lightIndex] = true;
  51450. }
  51451. };
  51452. /**
  51453. * This binds shadow lights related to the standard BJS materials.
  51454. * It implies the unifroms available on the materials are the standard BJS ones.
  51455. */
  51456. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  51457. var light = this._light;
  51458. var scene = this._scene;
  51459. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51460. return;
  51461. }
  51462. var camera = scene.activeCamera;
  51463. if (!camera) {
  51464. return;
  51465. }
  51466. var shadowMap = this.getShadowMap();
  51467. if (!shadowMap) {
  51468. return;
  51469. }
  51470. if (!light.needCube()) {
  51471. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  51472. }
  51473. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  51474. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  51475. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  51476. };
  51477. // Methods
  51478. /**
  51479. * Returns a Matrix object : the updated transformation matrix.
  51480. */
  51481. ShadowGenerator.prototype.getTransformMatrix = function () {
  51482. var scene = this._scene;
  51483. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  51484. return this._transformMatrix;
  51485. }
  51486. this._currentRenderID = scene.getRenderId();
  51487. this._currentFaceIndexCache = this._currentFaceIndex;
  51488. var lightPosition = this._light.position;
  51489. if (this._light.computeTransformedInformation()) {
  51490. lightPosition = this._light.transformedPosition;
  51491. }
  51492. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  51493. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  51494. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  51495. }
  51496. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  51497. this._cachedPosition = lightPosition.clone();
  51498. this._cachedDirection = this._lightDirection.clone();
  51499. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  51500. var shadowMap = this.getShadowMap();
  51501. if (shadowMap) {
  51502. var renderList = shadowMap.renderList;
  51503. if (renderList) {
  51504. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  51505. }
  51506. }
  51507. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  51508. }
  51509. return this._transformMatrix;
  51510. };
  51511. ShadowGenerator.prototype.recreateShadowMap = function () {
  51512. var shadowMap = this._shadowMap;
  51513. if (!shadowMap) {
  51514. return;
  51515. }
  51516. // Track render list.
  51517. var renderList = shadowMap.renderList;
  51518. // Clean up existing data.
  51519. this._disposeRTTandPostProcesses();
  51520. // Reinitializes.
  51521. this._initializeGenerator();
  51522. // Reaffect the filter to ensure a correct fallback if necessary.
  51523. this.filter = this.filter;
  51524. // Reaffect the filter.
  51525. this._applyFilterValues();
  51526. // Reaffect Render List.
  51527. this._shadowMap.renderList = renderList;
  51528. };
  51529. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  51530. if (this._shadowMap2) {
  51531. this._shadowMap2.dispose();
  51532. this._shadowMap2 = null;
  51533. }
  51534. if (this._downSamplePostprocess) {
  51535. this._downSamplePostprocess.dispose();
  51536. this._downSamplePostprocess = null;
  51537. }
  51538. if (this._boxBlurPostprocess) {
  51539. this._boxBlurPostprocess.dispose();
  51540. this._boxBlurPostprocess = null;
  51541. }
  51542. if (this._kernelBlurXPostprocess) {
  51543. this._kernelBlurXPostprocess.dispose();
  51544. this._kernelBlurXPostprocess = null;
  51545. }
  51546. if (this._kernelBlurYPostprocess) {
  51547. this._kernelBlurYPostprocess.dispose();
  51548. this._kernelBlurYPostprocess = null;
  51549. }
  51550. this._blurPostProcesses = [];
  51551. };
  51552. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  51553. if (this._shadowMap) {
  51554. this._shadowMap.dispose();
  51555. this._shadowMap = null;
  51556. }
  51557. this._disposeBlurPostProcesses();
  51558. };
  51559. /**
  51560. * Disposes the ShadowGenerator.
  51561. * Returns nothing.
  51562. */
  51563. ShadowGenerator.prototype.dispose = function () {
  51564. this._disposeRTTandPostProcesses();
  51565. if (this._light) {
  51566. this._light._shadowGenerator = null;
  51567. this._light._markMeshesAsLightDirty();
  51568. }
  51569. };
  51570. /**
  51571. * Serializes the ShadowGenerator and returns a serializationObject.
  51572. */
  51573. ShadowGenerator.prototype.serialize = function () {
  51574. var serializationObject = {};
  51575. var shadowMap = this.getShadowMap();
  51576. if (!shadowMap) {
  51577. return serializationObject;
  51578. }
  51579. serializationObject.lightId = this._light.id;
  51580. serializationObject.mapSize = shadowMap.getRenderSize();
  51581. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  51582. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  51583. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51584. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51585. serializationObject.usePoissonSampling = this.usePoissonSampling;
  51586. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  51587. serializationObject.depthScale = this.depthScale;
  51588. serializationObject.darkness = this.getDarkness();
  51589. serializationObject.blurBoxOffset = this.blurBoxOffset;
  51590. serializationObject.blurKernel = this.blurKernel;
  51591. serializationObject.blurScale = this.blurScale;
  51592. serializationObject.useKernelBlur = this.useKernelBlur;
  51593. serializationObject.transparencyShadow = this._transparencyShadow;
  51594. serializationObject.renderList = [];
  51595. if (shadowMap.renderList) {
  51596. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  51597. var mesh = shadowMap.renderList[meshIndex];
  51598. serializationObject.renderList.push(mesh.id);
  51599. }
  51600. }
  51601. return serializationObject;
  51602. };
  51603. /**
  51604. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  51605. */
  51606. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  51607. //casting to point light, as light is missing the position attr and typescript complains.
  51608. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  51609. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  51610. var shadowMap = shadowGenerator.getShadowMap();
  51611. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  51612. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  51613. meshes.forEach(function (mesh) {
  51614. if (!shadowMap) {
  51615. return;
  51616. }
  51617. if (!shadowMap.renderList) {
  51618. shadowMap.renderList = [];
  51619. }
  51620. shadowMap.renderList.push(mesh);
  51621. });
  51622. }
  51623. if (parsedShadowGenerator.usePoissonSampling) {
  51624. shadowGenerator.usePoissonSampling = true;
  51625. }
  51626. else if (parsedShadowGenerator.useExponentialShadowMap) {
  51627. shadowGenerator.useExponentialShadowMap = true;
  51628. }
  51629. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  51630. shadowGenerator.useBlurExponentialShadowMap = true;
  51631. }
  51632. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  51633. shadowGenerator.useCloseExponentialShadowMap = true;
  51634. }
  51635. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  51636. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  51637. }
  51638. else if (parsedShadowGenerator.useVarianceShadowMap) {
  51639. shadowGenerator.useExponentialShadowMap = true;
  51640. }
  51641. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  51642. shadowGenerator.useBlurExponentialShadowMap = true;
  51643. }
  51644. if (parsedShadowGenerator.depthScale) {
  51645. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  51646. }
  51647. if (parsedShadowGenerator.blurScale) {
  51648. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  51649. }
  51650. if (parsedShadowGenerator.blurBoxOffset) {
  51651. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  51652. }
  51653. if (parsedShadowGenerator.useKernelBlur) {
  51654. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  51655. }
  51656. if (parsedShadowGenerator.blurKernel) {
  51657. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  51658. }
  51659. if (parsedShadowGenerator.bias !== undefined) {
  51660. shadowGenerator.bias = parsedShadowGenerator.bias;
  51661. }
  51662. if (parsedShadowGenerator.darkness) {
  51663. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  51664. }
  51665. if (parsedShadowGenerator.transparencyShadow) {
  51666. shadowGenerator.setTransparencyShadow(true);
  51667. }
  51668. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  51669. return shadowGenerator;
  51670. };
  51671. ShadowGenerator._FILTER_NONE = 0;
  51672. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  51673. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  51674. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  51675. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  51676. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  51677. return ShadowGenerator;
  51678. }());
  51679. BABYLON.ShadowGenerator = ShadowGenerator;
  51680. })(BABYLON || (BABYLON = {}));
  51681. //# sourceMappingURL=babylon.shadowGenerator.js.map
  51682. var BABYLON;
  51683. (function (BABYLON) {
  51684. var DefaultLoadingScreen = /** @class */ (function () {
  51685. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  51686. if (_loadingText === void 0) { _loadingText = ""; }
  51687. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  51688. var _this = this;
  51689. this._renderingCanvas = _renderingCanvas;
  51690. this._loadingText = _loadingText;
  51691. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  51692. // Resize
  51693. this._resizeLoadingUI = function () {
  51694. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  51695. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  51696. if (!_this._loadingDiv) {
  51697. return;
  51698. }
  51699. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  51700. _this._loadingDiv.style.left = canvasRect.left + "px";
  51701. _this._loadingDiv.style.top = canvasRect.top + "px";
  51702. _this._loadingDiv.style.width = canvasRect.width + "px";
  51703. _this._loadingDiv.style.height = canvasRect.height + "px";
  51704. };
  51705. }
  51706. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  51707. if (this._loadingDiv) {
  51708. // Do not add a loading screen if there is already one
  51709. return;
  51710. }
  51711. this._loadingDiv = document.createElement("div");
  51712. this._loadingDiv.id = "babylonjsLoadingDiv";
  51713. this._loadingDiv.style.opacity = "0";
  51714. this._loadingDiv.style.transition = "opacity 1.5s ease";
  51715. this._loadingDiv.style.pointerEvents = "none";
  51716. // Loading text
  51717. this._loadingTextDiv = document.createElement("div");
  51718. this._loadingTextDiv.style.position = "absolute";
  51719. this._loadingTextDiv.style.left = "0";
  51720. this._loadingTextDiv.style.top = "50%";
  51721. this._loadingTextDiv.style.marginTop = "80px";
  51722. this._loadingTextDiv.style.width = "100%";
  51723. this._loadingTextDiv.style.height = "20px";
  51724. this._loadingTextDiv.style.fontFamily = "Arial";
  51725. this._loadingTextDiv.style.fontSize = "14px";
  51726. this._loadingTextDiv.style.color = "white";
  51727. this._loadingTextDiv.style.textAlign = "center";
  51728. this._loadingTextDiv.innerHTML = "Loading";
  51729. this._loadingDiv.appendChild(this._loadingTextDiv);
  51730. //set the predefined text
  51731. this._loadingTextDiv.innerHTML = this._loadingText;
  51732. // Generating keyframes
  51733. var style = document.createElement('style');
  51734. style.type = 'text/css';
  51735. 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 }";
  51736. style.innerHTML = keyFrames;
  51737. document.getElementsByTagName('head')[0].appendChild(style);
  51738. // Loading img
  51739. var imgBack = new Image();
  51740. 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";
  51741. imgBack.style.position = "absolute";
  51742. imgBack.style.left = "50%";
  51743. imgBack.style.top = "50%";
  51744. imgBack.style.marginLeft = "-60px";
  51745. imgBack.style.marginTop = "-60px";
  51746. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  51747. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  51748. imgBack.style.transformOrigin = "50% 50%";
  51749. imgBack.style.webkitTransformOrigin = "50% 50%";
  51750. this._loadingDiv.appendChild(imgBack);
  51751. this._resizeLoadingUI();
  51752. window.addEventListener("resize", this._resizeLoadingUI);
  51753. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51754. document.body.appendChild(this._loadingDiv);
  51755. this._loadingDiv.style.opacity = "1";
  51756. };
  51757. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  51758. var _this = this;
  51759. if (!this._loadingDiv) {
  51760. return;
  51761. }
  51762. var onTransitionEnd = function () {
  51763. if (!_this._loadingDiv) {
  51764. return;
  51765. }
  51766. document.body.removeChild(_this._loadingDiv);
  51767. window.removeEventListener("resize", _this._resizeLoadingUI);
  51768. _this._loadingDiv = null;
  51769. };
  51770. this._loadingDiv.style.opacity = "0";
  51771. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  51772. };
  51773. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  51774. set: function (text) {
  51775. this._loadingText = text;
  51776. if (this._loadingTextDiv) {
  51777. this._loadingTextDiv.innerHTML = this._loadingText;
  51778. }
  51779. },
  51780. enumerable: true,
  51781. configurable: true
  51782. });
  51783. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  51784. get: function () {
  51785. return this._loadingDivBackgroundColor;
  51786. },
  51787. set: function (color) {
  51788. this._loadingDivBackgroundColor = color;
  51789. if (!this._loadingDiv) {
  51790. return;
  51791. }
  51792. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51793. },
  51794. enumerable: true,
  51795. configurable: true
  51796. });
  51797. return DefaultLoadingScreen;
  51798. }());
  51799. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  51800. })(BABYLON || (BABYLON = {}));
  51801. //# sourceMappingURL=babylon.loadingScreen.js.map
  51802. var BABYLON;
  51803. (function (BABYLON) {
  51804. var SceneLoader = /** @class */ (function () {
  51805. function SceneLoader() {
  51806. }
  51807. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  51808. get: function () {
  51809. return 0;
  51810. },
  51811. enumerable: true,
  51812. configurable: true
  51813. });
  51814. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  51815. get: function () {
  51816. return 1;
  51817. },
  51818. enumerable: true,
  51819. configurable: true
  51820. });
  51821. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  51822. get: function () {
  51823. return 2;
  51824. },
  51825. enumerable: true,
  51826. configurable: true
  51827. });
  51828. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  51829. get: function () {
  51830. return 3;
  51831. },
  51832. enumerable: true,
  51833. configurable: true
  51834. });
  51835. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  51836. get: function () {
  51837. return SceneLoader._ForceFullSceneLoadingForIncremental;
  51838. },
  51839. set: function (value) {
  51840. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  51841. },
  51842. enumerable: true,
  51843. configurable: true
  51844. });
  51845. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  51846. get: function () {
  51847. return SceneLoader._ShowLoadingScreen;
  51848. },
  51849. set: function (value) {
  51850. SceneLoader._ShowLoadingScreen = value;
  51851. },
  51852. enumerable: true,
  51853. configurable: true
  51854. });
  51855. Object.defineProperty(SceneLoader, "loggingLevel", {
  51856. get: function () {
  51857. return SceneLoader._loggingLevel;
  51858. },
  51859. set: function (value) {
  51860. SceneLoader._loggingLevel = value;
  51861. },
  51862. enumerable: true,
  51863. configurable: true
  51864. });
  51865. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  51866. get: function () {
  51867. return SceneLoader._CleanBoneMatrixWeights;
  51868. },
  51869. set: function (value) {
  51870. SceneLoader._CleanBoneMatrixWeights = value;
  51871. },
  51872. enumerable: true,
  51873. configurable: true
  51874. });
  51875. SceneLoader._getDefaultPlugin = function () {
  51876. return SceneLoader._registeredPlugins[".babylon"];
  51877. };
  51878. SceneLoader._getPluginForExtension = function (extension) {
  51879. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  51880. if (registeredPlugin) {
  51881. return registeredPlugin;
  51882. }
  51883. return SceneLoader._getDefaultPlugin();
  51884. };
  51885. SceneLoader._getPluginForDirectLoad = function (data) {
  51886. for (var extension in SceneLoader._registeredPlugins) {
  51887. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  51888. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  51889. return SceneLoader._registeredPlugins[extension];
  51890. }
  51891. }
  51892. return SceneLoader._getDefaultPlugin();
  51893. };
  51894. SceneLoader._getPluginForFilename = function (sceneFilename) {
  51895. if (sceneFilename.name) {
  51896. sceneFilename = sceneFilename.name;
  51897. }
  51898. var dotPosition = sceneFilename.lastIndexOf(".");
  51899. var queryStringPosition = sceneFilename.indexOf("?");
  51900. if (queryStringPosition === -1) {
  51901. queryStringPosition = sceneFilename.length;
  51902. }
  51903. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  51904. return SceneLoader._getPluginForExtension(extension);
  51905. };
  51906. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  51907. SceneLoader._getDirectLoad = function (sceneFilename) {
  51908. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  51909. return sceneFilename.substr(5);
  51910. }
  51911. return null;
  51912. };
  51913. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  51914. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  51915. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  51916. var plugin = registeredPlugin.plugin;
  51917. var useArrayBuffer = registeredPlugin.isBinary;
  51918. var database;
  51919. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  51920. var dataCallback = function (data) {
  51921. if (scene.isDisposed) {
  51922. onError("Scene has been disposed");
  51923. return;
  51924. }
  51925. scene.database = database;
  51926. try {
  51927. onSuccess(plugin, data);
  51928. }
  51929. catch (e) {
  51930. onError(null, e);
  51931. }
  51932. };
  51933. var manifestChecked = function (success) {
  51934. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  51935. if (request) {
  51936. onError(request.status + " " + request.statusText);
  51937. }
  51938. });
  51939. };
  51940. if (directLoad) {
  51941. dataCallback(directLoad);
  51942. return;
  51943. }
  51944. if (rootUrl.indexOf("file:") === -1) {
  51945. if (scene.getEngine().enableOfflineSupport) {
  51946. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  51947. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  51948. }
  51949. else {
  51950. manifestChecked(true);
  51951. }
  51952. }
  51953. else {
  51954. var fileOrString = sceneFilename;
  51955. if (fileOrString.name) {
  51956. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  51957. }
  51958. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  51959. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  51960. }
  51961. else {
  51962. onError("Unable to find file named " + sceneFilename);
  51963. return;
  51964. }
  51965. }
  51966. };
  51967. // Public functions
  51968. SceneLoader.GetPluginForExtension = function (extension) {
  51969. return SceneLoader._getPluginForExtension(extension).plugin;
  51970. };
  51971. SceneLoader.RegisterPlugin = function (plugin) {
  51972. if (typeof plugin.extensions === "string") {
  51973. var extension = plugin.extensions;
  51974. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51975. plugin: plugin,
  51976. isBinary: false
  51977. };
  51978. }
  51979. else {
  51980. var extensions = plugin.extensions;
  51981. Object.keys(extensions).forEach(function (extension) {
  51982. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51983. plugin: plugin,
  51984. isBinary: extensions[extension].isBinary
  51985. };
  51986. });
  51987. }
  51988. };
  51989. /**
  51990. * Import meshes into a scene
  51991. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  51992. * @param rootUrl a string that defines the root url for scene and resources
  51993. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51994. * @param scene the instance of BABYLON.Scene to append to
  51995. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  51996. * @param onProgress a callback with a progress event for each file being loaded
  51997. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51998. */
  51999. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52000. if (onSuccess === void 0) { onSuccess = null; }
  52001. if (onProgress === void 0) { onProgress = null; }
  52002. if (onError === void 0) { onError = null; }
  52003. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52004. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52005. return;
  52006. }
  52007. var loadingToken = {};
  52008. scene._addPendingData(loadingToken);
  52009. var errorHandler = function (message, exception) {
  52010. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52011. if (onError) {
  52012. onError(scene, errorMessage, exception);
  52013. }
  52014. else {
  52015. BABYLON.Tools.Error(errorMessage);
  52016. // should the exception be thrown?
  52017. }
  52018. scene._removePendingData(loadingToken);
  52019. };
  52020. var progressHandler = function (event) {
  52021. if (onProgress) {
  52022. onProgress(event);
  52023. }
  52024. };
  52025. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52026. if (plugin.importMesh) {
  52027. var syncedPlugin = plugin;
  52028. var meshes = new Array();
  52029. var particleSystems = new Array();
  52030. var skeletons = new Array();
  52031. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  52032. return;
  52033. }
  52034. if (onSuccess) {
  52035. // wrap onSuccess with try-catch to know if something went wrong.
  52036. try {
  52037. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52038. onSuccess(meshes, particleSystems, skeletons);
  52039. scene._removePendingData(loadingToken);
  52040. }
  52041. catch (e) {
  52042. var message = 'Error in onSuccess callback.';
  52043. errorHandler(message, e);
  52044. }
  52045. }
  52046. }
  52047. else {
  52048. var asyncedPlugin = plugin;
  52049. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  52050. if (onSuccess) {
  52051. try {
  52052. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52053. onSuccess(meshes, particleSystems, skeletons);
  52054. scene._removePendingData(loadingToken);
  52055. }
  52056. catch (e) {
  52057. var message = 'Error in onSuccess callback.';
  52058. errorHandler(message, e);
  52059. }
  52060. }
  52061. }, progressHandler, errorHandler);
  52062. }
  52063. }, progressHandler, errorHandler, pluginExtension);
  52064. };
  52065. /**
  52066. * Load a scene
  52067. * @param rootUrl a string that defines the root url for scene and resources
  52068. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52069. * @param engine is the instance of BABYLON.Engine to use to create the scene
  52070. * @param onSuccess a callback with the scene when import succeeds
  52071. * @param onProgress a callback with a progress event for each file being loaded
  52072. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52073. */
  52074. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  52075. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  52076. };
  52077. /**
  52078. * Append a scene
  52079. * @param rootUrl a string that defines the root url for scene and resources
  52080. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52081. * @param scene is the instance of BABYLON.Scene to append to
  52082. * @param onSuccess a callback with the scene when import succeeds
  52083. * @param onProgress a callback with a progress event for each file being loaded
  52084. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52085. */
  52086. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52087. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52088. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52089. return;
  52090. }
  52091. if (SceneLoader.ShowLoadingScreen) {
  52092. scene.getEngine().displayLoadingUI();
  52093. }
  52094. var loadingToken = {};
  52095. scene._addPendingData(loadingToken);
  52096. var errorHandler = function (message, exception) {
  52097. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52098. if (onError) {
  52099. onError(scene, errorMessage, exception);
  52100. }
  52101. else {
  52102. BABYLON.Tools.Error(errorMessage);
  52103. // should the exception be thrown?
  52104. }
  52105. scene._removePendingData(loadingToken);
  52106. scene.getEngine().hideLoadingUI();
  52107. };
  52108. var progressHandler = function (event) {
  52109. if (onProgress) {
  52110. onProgress(event);
  52111. }
  52112. };
  52113. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52114. if (plugin.load) {
  52115. var syncedPlugin = plugin;
  52116. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  52117. return;
  52118. }
  52119. if (onSuccess) {
  52120. try {
  52121. onSuccess(scene);
  52122. }
  52123. catch (e) {
  52124. errorHandler("Error in onSuccess callback", e);
  52125. }
  52126. }
  52127. scene.loadingPluginName = plugin.name;
  52128. scene._removePendingData(loadingToken);
  52129. }
  52130. else {
  52131. var asyncedPlugin = plugin;
  52132. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  52133. if (onSuccess) {
  52134. onSuccess(scene);
  52135. }
  52136. scene.loadingPluginName = plugin.name;
  52137. scene._removePendingData(loadingToken);
  52138. }, progressHandler, errorHandler);
  52139. }
  52140. if (SceneLoader.ShowLoadingScreen) {
  52141. scene.executeWhenReady(function () {
  52142. scene.getEngine().hideLoadingUI();
  52143. });
  52144. }
  52145. }, progressHandler, errorHandler, pluginExtension);
  52146. };
  52147. // Flags
  52148. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  52149. SceneLoader._ShowLoadingScreen = true;
  52150. SceneLoader._CleanBoneMatrixWeights = false;
  52151. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  52152. // Members
  52153. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  52154. SceneLoader._registeredPlugins = {};
  52155. return SceneLoader;
  52156. }());
  52157. BABYLON.SceneLoader = SceneLoader;
  52158. ;
  52159. })(BABYLON || (BABYLON = {}));
  52160. //# sourceMappingURL=babylon.sceneLoader.js.map
  52161. var BABYLON;
  52162. (function (BABYLON) {
  52163. var Internals;
  52164. (function (Internals) {
  52165. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52166. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52167. var parsedMaterial = parsedData.materials[index];
  52168. if (parsedMaterial.id === id) {
  52169. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52170. }
  52171. }
  52172. return null;
  52173. };
  52174. var isDescendantOf = function (mesh, names, hierarchyIds) {
  52175. for (var i in names) {
  52176. if (mesh.name === names[i]) {
  52177. hierarchyIds.push(mesh.id);
  52178. return true;
  52179. }
  52180. }
  52181. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  52182. hierarchyIds.push(mesh.id);
  52183. return true;
  52184. }
  52185. return false;
  52186. };
  52187. var logOperation = function (operation, producer) {
  52188. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  52189. };
  52190. BABYLON.SceneLoader.RegisterPlugin({
  52191. name: "babylon.js",
  52192. extensions: ".babylon",
  52193. canDirectLoad: function (data) {
  52194. if (data.indexOf("babylon") !== -1) {
  52195. return true;
  52196. }
  52197. return false;
  52198. },
  52199. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  52200. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52201. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52202. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52203. // and avoid problems with multiple concurrent .babylon loads.
  52204. var log = "importMesh has failed JSON parse";
  52205. try {
  52206. var parsedData = JSON.parse(data);
  52207. log = "";
  52208. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52209. if (!meshesNames) {
  52210. meshesNames = null;
  52211. }
  52212. else if (!Array.isArray(meshesNames)) {
  52213. meshesNames = [meshesNames];
  52214. }
  52215. var hierarchyIds = new Array();
  52216. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52217. var loadedSkeletonsIds = [];
  52218. var loadedMaterialsIds = [];
  52219. var index;
  52220. var cache;
  52221. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52222. var parsedMesh = parsedData.meshes[index];
  52223. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  52224. if (meshesNames !== null) {
  52225. // Remove found mesh name from list.
  52226. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  52227. }
  52228. //Geometry?
  52229. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  52230. //does the file contain geometries?
  52231. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  52232. //find the correct geometry and add it to the scene
  52233. var found = false;
  52234. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  52235. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  52236. return;
  52237. }
  52238. else {
  52239. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  52240. if (parsedGeometryData.id === parsedMesh.geometryId) {
  52241. switch (geometryType) {
  52242. case "boxes":
  52243. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  52244. break;
  52245. case "spheres":
  52246. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  52247. break;
  52248. case "cylinders":
  52249. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  52250. break;
  52251. case "toruses":
  52252. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  52253. break;
  52254. case "grounds":
  52255. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  52256. break;
  52257. case "planes":
  52258. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  52259. break;
  52260. case "torusKnots":
  52261. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  52262. break;
  52263. case "vertexData":
  52264. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  52265. break;
  52266. }
  52267. found = true;
  52268. }
  52269. });
  52270. }
  52271. });
  52272. if (found === false) {
  52273. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  52274. }
  52275. }
  52276. }
  52277. // Material ?
  52278. if (parsedMesh.materialId) {
  52279. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  52280. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52281. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  52282. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  52283. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  52284. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  52285. var subMatId = parsedMultiMaterial.materials[matIndex];
  52286. loadedMaterialsIds.push(subMatId);
  52287. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  52288. log += "\n\tMaterial " + mat.toString(fullDetails);
  52289. }
  52290. loadedMaterialsIds.push(parsedMultiMaterial.id);
  52291. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52292. materialFound = true;
  52293. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  52294. break;
  52295. }
  52296. }
  52297. }
  52298. if (materialFound === false) {
  52299. loadedMaterialsIds.push(parsedMesh.materialId);
  52300. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  52301. if (!mat) {
  52302. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  52303. }
  52304. else {
  52305. log += "\n\tMaterial " + mat.toString(fullDetails);
  52306. }
  52307. }
  52308. }
  52309. // Skeleton ?
  52310. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52311. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  52312. if (skeletonAlreadyLoaded === false) {
  52313. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  52314. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  52315. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  52316. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52317. skeletons.push(skeleton);
  52318. loadedSkeletonsIds.push(parsedSkeleton.id);
  52319. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  52320. }
  52321. }
  52322. }
  52323. }
  52324. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52325. meshes.push(mesh);
  52326. log += "\n\tMesh " + mesh.toString(fullDetails);
  52327. }
  52328. }
  52329. // Connecting parents
  52330. var currentMesh;
  52331. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52332. currentMesh = scene.meshes[index];
  52333. if (currentMesh._waitingParentId) {
  52334. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  52335. currentMesh._waitingParentId = null;
  52336. }
  52337. }
  52338. // freeze and compute world matrix application
  52339. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52340. currentMesh = scene.meshes[index];
  52341. if (currentMesh._waitingFreezeWorldMatrix) {
  52342. currentMesh.freezeWorldMatrix();
  52343. currentMesh._waitingFreezeWorldMatrix = null;
  52344. }
  52345. else {
  52346. currentMesh.computeWorldMatrix(true);
  52347. }
  52348. }
  52349. }
  52350. // Particles
  52351. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52352. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52353. var parsedParticleSystem = parsedData.particleSystems[index];
  52354. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  52355. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  52356. }
  52357. }
  52358. }
  52359. return true;
  52360. }
  52361. catch (err) {
  52362. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  52363. if (onError) {
  52364. onError(msg, err);
  52365. }
  52366. else {
  52367. BABYLON.Tools.Log(msg);
  52368. throw err;
  52369. }
  52370. }
  52371. finally {
  52372. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52373. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52374. }
  52375. }
  52376. return false;
  52377. },
  52378. load: function (scene, data, rootUrl, onError) {
  52379. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52380. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52381. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52382. // and avoid problems with multiple concurrent .babylon loads.
  52383. var log = "importScene has failed JSON parse";
  52384. try {
  52385. var parsedData = JSON.parse(data);
  52386. log = "";
  52387. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52388. // Scene
  52389. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  52390. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  52391. }
  52392. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  52393. scene.autoClear = parsedData.autoClear;
  52394. }
  52395. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  52396. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  52397. }
  52398. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  52399. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  52400. }
  52401. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  52402. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  52403. }
  52404. // Fog
  52405. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  52406. scene.fogMode = parsedData.fogMode;
  52407. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  52408. scene.fogStart = parsedData.fogStart;
  52409. scene.fogEnd = parsedData.fogEnd;
  52410. scene.fogDensity = parsedData.fogDensity;
  52411. log += "\tFog mode for scene: ";
  52412. switch (scene.fogMode) {
  52413. // getters not compiling, so using hardcoded
  52414. case 1:
  52415. log += "exp\n";
  52416. break;
  52417. case 2:
  52418. log += "exp2\n";
  52419. break;
  52420. case 3:
  52421. log += "linear\n";
  52422. break;
  52423. }
  52424. }
  52425. //Physics
  52426. if (parsedData.physicsEnabled) {
  52427. var physicsPlugin;
  52428. if (parsedData.physicsEngine === "cannon") {
  52429. physicsPlugin = new BABYLON.CannonJSPlugin();
  52430. }
  52431. else if (parsedData.physicsEngine === "oimo") {
  52432. physicsPlugin = new BABYLON.OimoJSPlugin();
  52433. }
  52434. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  52435. //else - default engine, which is currently oimo
  52436. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  52437. scene.enablePhysics(physicsGravity, physicsPlugin);
  52438. }
  52439. // Metadata
  52440. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  52441. scene.metadata = parsedData.metadata;
  52442. }
  52443. //collisions, if defined. otherwise, default is true
  52444. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  52445. scene.collisionsEnabled = parsedData.collisionsEnabled;
  52446. }
  52447. scene.workerCollisions = !!parsedData.workerCollisions;
  52448. var index;
  52449. var cache;
  52450. // Lights
  52451. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  52452. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  52453. var parsedLight = parsedData.lights[index];
  52454. var light = BABYLON.Light.Parse(parsedLight, scene);
  52455. if (light) {
  52456. log += (index === 0 ? "\n\tLights:" : "");
  52457. log += "\n\t\t" + light.toString(fullDetails);
  52458. }
  52459. }
  52460. }
  52461. // Animations
  52462. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  52463. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  52464. var parsedAnimation = parsedData.animations[index];
  52465. var animation = BABYLON.Animation.Parse(parsedAnimation);
  52466. scene.animations.push(animation);
  52467. log += (index === 0 ? "\n\tAnimations:" : "");
  52468. log += "\n\t\t" + animation.toString(fullDetails);
  52469. }
  52470. }
  52471. if (parsedData.autoAnimate) {
  52472. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  52473. }
  52474. // Materials
  52475. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  52476. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52477. var parsedMaterial = parsedData.materials[index];
  52478. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52479. log += (index === 0 ? "\n\tMaterials:" : "");
  52480. log += "\n\t\t" + mat.toString(fullDetails);
  52481. }
  52482. }
  52483. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52484. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  52485. var parsedMultiMaterial = parsedData.multiMaterials[index];
  52486. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52487. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  52488. log += "\n\t\t" + mmat.toString(fullDetails);
  52489. }
  52490. }
  52491. // Morph targets
  52492. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  52493. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  52494. var managerData = _a[_i];
  52495. BABYLON.MorphTargetManager.Parse(managerData, scene);
  52496. }
  52497. }
  52498. // Skeletons
  52499. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52500. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  52501. var parsedSkeleton = parsedData.skeletons[index];
  52502. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52503. log += (index === 0 ? "\n\tSkeletons:" : "");
  52504. log += "\n\t\t" + skeleton.toString(fullDetails);
  52505. }
  52506. }
  52507. // Geometries
  52508. var geometries = parsedData.geometries;
  52509. if (geometries !== undefined && geometries !== null) {
  52510. // Boxes
  52511. var boxes = geometries.boxes;
  52512. if (boxes !== undefined && boxes !== null) {
  52513. for (index = 0, cache = boxes.length; index < cache; index++) {
  52514. var parsedBox = boxes[index];
  52515. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  52516. }
  52517. }
  52518. // Spheres
  52519. var spheres = geometries.spheres;
  52520. if (spheres !== undefined && spheres !== null) {
  52521. for (index = 0, cache = spheres.length; index < cache; index++) {
  52522. var parsedSphere = spheres[index];
  52523. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  52524. }
  52525. }
  52526. // Cylinders
  52527. var cylinders = geometries.cylinders;
  52528. if (cylinders !== undefined && cylinders !== null) {
  52529. for (index = 0, cache = cylinders.length; index < cache; index++) {
  52530. var parsedCylinder = cylinders[index];
  52531. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  52532. }
  52533. }
  52534. // Toruses
  52535. var toruses = geometries.toruses;
  52536. if (toruses !== undefined && toruses !== null) {
  52537. for (index = 0, cache = toruses.length; index < cache; index++) {
  52538. var parsedTorus = toruses[index];
  52539. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  52540. }
  52541. }
  52542. // Grounds
  52543. var grounds = geometries.grounds;
  52544. if (grounds !== undefined && grounds !== null) {
  52545. for (index = 0, cache = grounds.length; index < cache; index++) {
  52546. var parsedGround = grounds[index];
  52547. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  52548. }
  52549. }
  52550. // Planes
  52551. var planes = geometries.planes;
  52552. if (planes !== undefined && planes !== null) {
  52553. for (index = 0, cache = planes.length; index < cache; index++) {
  52554. var parsedPlane = planes[index];
  52555. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  52556. }
  52557. }
  52558. // TorusKnots
  52559. var torusKnots = geometries.torusKnots;
  52560. if (torusKnots !== undefined && torusKnots !== null) {
  52561. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  52562. var parsedTorusKnot = torusKnots[index];
  52563. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  52564. }
  52565. }
  52566. // VertexData
  52567. var vertexData = geometries.vertexData;
  52568. if (vertexData !== undefined && vertexData !== null) {
  52569. for (index = 0, cache = vertexData.length; index < cache; index++) {
  52570. var parsedVertexData = vertexData[index];
  52571. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  52572. }
  52573. }
  52574. }
  52575. // Meshes
  52576. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52577. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52578. var parsedMesh = parsedData.meshes[index];
  52579. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52580. log += (index === 0 ? "\n\tMeshes:" : "");
  52581. log += "\n\t\t" + mesh.toString(fullDetails);
  52582. }
  52583. }
  52584. // Cameras
  52585. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  52586. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  52587. var parsedCamera = parsedData.cameras[index];
  52588. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  52589. log += (index === 0 ? "\n\tCameras:" : "");
  52590. log += "\n\t\t" + camera.toString(fullDetails);
  52591. }
  52592. }
  52593. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  52594. scene.setActiveCameraByID(parsedData.activeCameraID);
  52595. }
  52596. // Browsing all the graph to connect the dots
  52597. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  52598. var camera = scene.cameras[index];
  52599. if (camera._waitingParentId) {
  52600. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  52601. camera._waitingParentId = null;
  52602. }
  52603. }
  52604. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52605. var light_1 = scene.lights[index];
  52606. if (light_1 && light_1._waitingParentId) {
  52607. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  52608. light_1._waitingParentId = null;
  52609. }
  52610. }
  52611. // Sounds
  52612. var loadedSounds = [];
  52613. var loadedSound;
  52614. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  52615. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  52616. var parsedSound = parsedData.sounds[index];
  52617. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52618. if (!parsedSound.url)
  52619. parsedSound.url = parsedSound.name;
  52620. if (!loadedSounds[parsedSound.url]) {
  52621. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  52622. loadedSounds[parsedSound.url] = loadedSound;
  52623. }
  52624. else {
  52625. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  52626. }
  52627. }
  52628. else {
  52629. new BABYLON.Sound(parsedSound.name, null, scene);
  52630. }
  52631. }
  52632. }
  52633. loadedSounds = [];
  52634. // Connect parents & children and parse actions
  52635. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52636. var mesh = scene.meshes[index];
  52637. if (mesh._waitingParentId) {
  52638. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  52639. mesh._waitingParentId = null;
  52640. }
  52641. if (mesh._waitingActions) {
  52642. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  52643. mesh._waitingActions = null;
  52644. }
  52645. }
  52646. // freeze world matrix application
  52647. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52648. var currentMesh = scene.meshes[index];
  52649. if (currentMesh._waitingFreezeWorldMatrix) {
  52650. currentMesh.freezeWorldMatrix();
  52651. currentMesh._waitingFreezeWorldMatrix = null;
  52652. }
  52653. else {
  52654. currentMesh.computeWorldMatrix(true);
  52655. }
  52656. }
  52657. // Particles Systems
  52658. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52659. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52660. var parsedParticleSystem = parsedData.particleSystems[index];
  52661. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  52662. }
  52663. }
  52664. // Environment texture
  52665. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  52666. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  52667. if (parsedData.createDefaultSkybox === true) {
  52668. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  52669. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  52670. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  52671. }
  52672. }
  52673. // Lens flares
  52674. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  52675. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  52676. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  52677. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  52678. }
  52679. }
  52680. // Shadows
  52681. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  52682. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  52683. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  52684. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  52685. }
  52686. }
  52687. // Lights exclusions / inclusions
  52688. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52689. var light_2 = scene.lights[index];
  52690. // Excluded check
  52691. if (light_2._excludedMeshesIds.length > 0) {
  52692. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  52693. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  52694. if (excludedMesh) {
  52695. light_2.excludedMeshes.push(excludedMesh);
  52696. }
  52697. }
  52698. light_2._excludedMeshesIds = [];
  52699. }
  52700. // Included check
  52701. if (light_2._includedOnlyMeshesIds.length > 0) {
  52702. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  52703. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  52704. if (includedOnlyMesh) {
  52705. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  52706. }
  52707. }
  52708. light_2._includedOnlyMeshesIds = [];
  52709. }
  52710. }
  52711. // Actions (scene)
  52712. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  52713. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  52714. }
  52715. // Finish
  52716. return true;
  52717. }
  52718. catch (err) {
  52719. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  52720. if (onError) {
  52721. onError(msg, err);
  52722. }
  52723. else {
  52724. BABYLON.Tools.Log(msg);
  52725. throw err;
  52726. }
  52727. }
  52728. finally {
  52729. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52730. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52731. }
  52732. }
  52733. return false;
  52734. }
  52735. });
  52736. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52737. })(BABYLON || (BABYLON = {}));
  52738. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  52739. var BABYLON;
  52740. (function (BABYLON) {
  52741. var FilesInput = /** @class */ (function () {
  52742. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  52743. this.onProcessFileCallback = function () { return true; };
  52744. this._engine = engine;
  52745. this._currentScene = scene;
  52746. this._sceneLoadedCallback = sceneLoadedCallback;
  52747. this._progressCallback = progressCallback;
  52748. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  52749. this._textureLoadingCallback = textureLoadingCallback;
  52750. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  52751. this._onReloadCallback = onReloadCallback;
  52752. this._errorCallback = errorCallback;
  52753. }
  52754. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  52755. var _this = this;
  52756. if (elementToMonitor) {
  52757. this._elementToMonitor = elementToMonitor;
  52758. this._dragEnterHandler = function (e) { _this.drag(e); };
  52759. this._dragOverHandler = function (e) { _this.drag(e); };
  52760. this._dropHandler = function (e) { _this.drop(e); };
  52761. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  52762. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  52763. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  52764. }
  52765. };
  52766. FilesInput.prototype.dispose = function () {
  52767. if (!this._elementToMonitor) {
  52768. return;
  52769. }
  52770. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  52771. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  52772. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  52773. };
  52774. FilesInput.prototype.renderFunction = function () {
  52775. if (this._additionalRenderLoopLogicCallback) {
  52776. this._additionalRenderLoopLogicCallback();
  52777. }
  52778. if (this._currentScene) {
  52779. if (this._textureLoadingCallback) {
  52780. var remaining = this._currentScene.getWaitingItemsCount();
  52781. if (remaining > 0) {
  52782. this._textureLoadingCallback(remaining);
  52783. }
  52784. }
  52785. this._currentScene.render();
  52786. }
  52787. };
  52788. FilesInput.prototype.drag = function (e) {
  52789. e.stopPropagation();
  52790. e.preventDefault();
  52791. };
  52792. FilesInput.prototype.drop = function (eventDrop) {
  52793. eventDrop.stopPropagation();
  52794. eventDrop.preventDefault();
  52795. this.loadFiles(eventDrop);
  52796. };
  52797. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  52798. var _this = this;
  52799. var reader = folder.createReader();
  52800. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  52801. reader.readEntries(function (entries) {
  52802. remaining.count += entries.length;
  52803. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  52804. var entry = entries_1[_i];
  52805. if (entry.isFile) {
  52806. entry.file(function (file) {
  52807. file.correctName = relativePath + file.name;
  52808. files.push(file);
  52809. if (--remaining.count === 0) {
  52810. callback();
  52811. }
  52812. });
  52813. }
  52814. else if (entry.isDirectory) {
  52815. _this._traverseFolder(entry, files, remaining, callback);
  52816. }
  52817. }
  52818. if (--remaining.count) {
  52819. callback();
  52820. }
  52821. });
  52822. };
  52823. FilesInput.prototype._processFiles = function (files) {
  52824. var skippedFiles = 0;
  52825. for (var i = 0; i < files.length; i++) {
  52826. var name = files[i].correctName.toLowerCase();
  52827. var extension = name.split('.').pop();
  52828. if (!this.onProcessFileCallback(files[i], name, extension)) {
  52829. skippedFiles++;
  52830. continue;
  52831. }
  52832. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  52833. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  52834. this._sceneFileToLoad = files[i];
  52835. }
  52836. else {
  52837. FilesInput.FilesToLoad[name] = files[i];
  52838. }
  52839. }
  52840. if (this._onReloadCallback) {
  52841. this._onReloadCallback(this._sceneFileToLoad);
  52842. }
  52843. else if (skippedFiles < files.length) {
  52844. this.reload();
  52845. }
  52846. };
  52847. FilesInput.prototype.loadFiles = function (event) {
  52848. var _this = this;
  52849. if (this._startingProcessingFilesCallback)
  52850. this._startingProcessingFilesCallback();
  52851. // Handling data transfer via drag'n'drop
  52852. if (event && event.dataTransfer && event.dataTransfer.files) {
  52853. this._filesToLoad = event.dataTransfer.files;
  52854. }
  52855. // Handling files from input files
  52856. if (event && event.target && event.target.files) {
  52857. this._filesToLoad = event.target.files;
  52858. }
  52859. if (this._filesToLoad && this._filesToLoad.length > 0) {
  52860. var files_1 = new Array();
  52861. var folders = [];
  52862. var items = event.dataTransfer ? event.dataTransfer.items : null;
  52863. for (var i = 0; i < this._filesToLoad.length; i++) {
  52864. var fileToLoad = this._filesToLoad[i];
  52865. var name_1 = fileToLoad.name.toLowerCase();
  52866. var entry = void 0;
  52867. fileToLoad.correctName = name_1;
  52868. if (items) {
  52869. var item = items[i];
  52870. if (item.getAsEntry) {
  52871. entry = item.getAsEntry();
  52872. }
  52873. else if (item.webkitGetAsEntry) {
  52874. entry = item.webkitGetAsEntry();
  52875. }
  52876. }
  52877. if (!entry) {
  52878. files_1.push(fileToLoad);
  52879. }
  52880. else {
  52881. if (entry.isDirectory) {
  52882. folders.push(entry);
  52883. }
  52884. else {
  52885. files_1.push(fileToLoad);
  52886. }
  52887. }
  52888. }
  52889. if (folders.length === 0) {
  52890. this._processFiles(files_1);
  52891. }
  52892. else {
  52893. var remaining = { count: folders.length };
  52894. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  52895. var folder = folders_1[_i];
  52896. this._traverseFolder(folder, files_1, remaining, function () {
  52897. _this._processFiles(files_1);
  52898. });
  52899. }
  52900. }
  52901. }
  52902. };
  52903. FilesInput.prototype.reload = function () {
  52904. var _this = this;
  52905. // If a ".babylon" file has been provided
  52906. if (this._sceneFileToLoad) {
  52907. if (this._currentScene) {
  52908. if (BABYLON.Tools.errorsCount > 0) {
  52909. BABYLON.Tools.ClearLogCache();
  52910. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  52911. }
  52912. this._engine.stopRenderLoop();
  52913. this._currentScene.dispose();
  52914. }
  52915. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  52916. _this._currentScene = newScene;
  52917. if (_this._sceneLoadedCallback) {
  52918. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  52919. }
  52920. // Wait for textures and shaders to be ready
  52921. _this._currentScene.executeWhenReady(function () {
  52922. _this._engine.runRenderLoop(function () {
  52923. _this.renderFunction();
  52924. });
  52925. });
  52926. }, function (progress) {
  52927. if (_this._progressCallback) {
  52928. _this._progressCallback(progress);
  52929. }
  52930. }, function (scene, message) {
  52931. _this._currentScene = scene;
  52932. if (_this._errorCallback) {
  52933. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  52934. }
  52935. });
  52936. }
  52937. else {
  52938. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  52939. }
  52940. };
  52941. FilesInput.FilesToLoad = {};
  52942. return FilesInput;
  52943. }());
  52944. BABYLON.FilesInput = FilesInput;
  52945. })(BABYLON || (BABYLON = {}));
  52946. //# sourceMappingURL=babylon.filesInput.js.map
  52947. var BABYLON;
  52948. (function (BABYLON) {
  52949. /**
  52950. * This class implement a typical dictionary using a string as key and the generic type T as value.
  52951. * The underlying implementation relies on an associative array to ensure the best performances.
  52952. * The value can be anything including 'null' but except 'undefined'
  52953. */
  52954. var StringDictionary = /** @class */ (function () {
  52955. function StringDictionary() {
  52956. this._count = 0;
  52957. this._data = {};
  52958. }
  52959. /**
  52960. * This will clear this dictionary and copy the content from the 'source' one.
  52961. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  52962. * @param source the dictionary to take the content from and copy to this dictionary
  52963. */
  52964. StringDictionary.prototype.copyFrom = function (source) {
  52965. var _this = this;
  52966. this.clear();
  52967. source.forEach(function (t, v) { return _this.add(t, v); });
  52968. };
  52969. /**
  52970. * Get a value based from its key
  52971. * @param key the given key to get the matching value from
  52972. * @return the value if found, otherwise undefined is returned
  52973. */
  52974. StringDictionary.prototype.get = function (key) {
  52975. var val = this._data[key];
  52976. if (val !== undefined) {
  52977. return val;
  52978. }
  52979. return undefined;
  52980. };
  52981. /**
  52982. * Get a value from its key or add it if it doesn't exist.
  52983. * This method will ensure you that a given key/data will be present in the dictionary.
  52984. * @param key the given key to get the matching value from
  52985. * @param factory the factory that will create the value if the key is not present in the dictionary.
  52986. * The factory will only be invoked if there's no data for the given key.
  52987. * @return the value corresponding to the key.
  52988. */
  52989. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  52990. var val = this.get(key);
  52991. if (val !== undefined) {
  52992. return val;
  52993. }
  52994. val = factory(key);
  52995. if (val) {
  52996. this.add(key, val);
  52997. }
  52998. return val;
  52999. };
  53000. /**
  53001. * Get a value from its key if present in the dictionary otherwise add it
  53002. * @param key the key to get the value from
  53003. * @param val if there's no such key/value pair in the dictionary add it with this value
  53004. * @return the value corresponding to the key
  53005. */
  53006. StringDictionary.prototype.getOrAdd = function (key, val) {
  53007. var curVal = this.get(key);
  53008. if (curVal !== undefined) {
  53009. return curVal;
  53010. }
  53011. this.add(key, val);
  53012. return val;
  53013. };
  53014. /**
  53015. * Check if there's a given key in the dictionary
  53016. * @param key the key to check for
  53017. * @return true if the key is present, false otherwise
  53018. */
  53019. StringDictionary.prototype.contains = function (key) {
  53020. return this._data[key] !== undefined;
  53021. };
  53022. /**
  53023. * Add a new key and its corresponding value
  53024. * @param key the key to add
  53025. * @param value the value corresponding to the key
  53026. * @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
  53027. */
  53028. StringDictionary.prototype.add = function (key, value) {
  53029. if (this._data[key] !== undefined) {
  53030. return false;
  53031. }
  53032. this._data[key] = value;
  53033. ++this._count;
  53034. return true;
  53035. };
  53036. StringDictionary.prototype.set = function (key, value) {
  53037. if (this._data[key] === undefined) {
  53038. return false;
  53039. }
  53040. this._data[key] = value;
  53041. return true;
  53042. };
  53043. /**
  53044. * Get the element of the given key and remove it from the dictionary
  53045. * @param key
  53046. */
  53047. StringDictionary.prototype.getAndRemove = function (key) {
  53048. var val = this.get(key);
  53049. if (val !== undefined) {
  53050. delete this._data[key];
  53051. --this._count;
  53052. return val;
  53053. }
  53054. return null;
  53055. };
  53056. /**
  53057. * Remove a key/value from the dictionary.
  53058. * @param key the key to remove
  53059. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  53060. */
  53061. StringDictionary.prototype.remove = function (key) {
  53062. if (this.contains(key)) {
  53063. delete this._data[key];
  53064. --this._count;
  53065. return true;
  53066. }
  53067. return false;
  53068. };
  53069. /**
  53070. * Clear the whole content of the dictionary
  53071. */
  53072. StringDictionary.prototype.clear = function () {
  53073. this._data = {};
  53074. this._count = 0;
  53075. };
  53076. Object.defineProperty(StringDictionary.prototype, "count", {
  53077. get: function () {
  53078. return this._count;
  53079. },
  53080. enumerable: true,
  53081. configurable: true
  53082. });
  53083. /**
  53084. * Execute a callback on each key/val of the dictionary.
  53085. * Note that you can remove any element in this dictionary in the callback implementation
  53086. * @param callback the callback to execute on a given key/value pair
  53087. */
  53088. StringDictionary.prototype.forEach = function (callback) {
  53089. for (var cur in this._data) {
  53090. var val = this._data[cur];
  53091. callback(cur, val);
  53092. }
  53093. };
  53094. /**
  53095. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  53096. * If the callback returns null or undefined the method will iterate to the next key/value pair
  53097. * Note that you can remove any element in this dictionary in the callback implementation
  53098. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  53099. */
  53100. StringDictionary.prototype.first = function (callback) {
  53101. for (var cur in this._data) {
  53102. var val = this._data[cur];
  53103. var res = callback(cur, val);
  53104. if (res) {
  53105. return res;
  53106. }
  53107. }
  53108. return null;
  53109. };
  53110. return StringDictionary;
  53111. }());
  53112. BABYLON.StringDictionary = StringDictionary;
  53113. })(BABYLON || (BABYLON = {}));
  53114. //# sourceMappingURL=babylon.stringDictionary.js.map
  53115. var BABYLON;
  53116. (function (BABYLON) {
  53117. var Tags = /** @class */ (function () {
  53118. function Tags() {
  53119. }
  53120. Tags.EnableFor = function (obj) {
  53121. obj._tags = obj._tags || {};
  53122. obj.hasTags = function () {
  53123. return Tags.HasTags(obj);
  53124. };
  53125. obj.addTags = function (tagsString) {
  53126. return Tags.AddTagsTo(obj, tagsString);
  53127. };
  53128. obj.removeTags = function (tagsString) {
  53129. return Tags.RemoveTagsFrom(obj, tagsString);
  53130. };
  53131. obj.matchesTagsQuery = function (tagsQuery) {
  53132. return Tags.MatchesQuery(obj, tagsQuery);
  53133. };
  53134. };
  53135. Tags.DisableFor = function (obj) {
  53136. delete obj._tags;
  53137. delete obj.hasTags;
  53138. delete obj.addTags;
  53139. delete obj.removeTags;
  53140. delete obj.matchesTagsQuery;
  53141. };
  53142. Tags.HasTags = function (obj) {
  53143. if (!obj._tags) {
  53144. return false;
  53145. }
  53146. return !BABYLON.Tools.IsEmpty(obj._tags);
  53147. };
  53148. Tags.GetTags = function (obj, asString) {
  53149. if (asString === void 0) { asString = true; }
  53150. if (!obj._tags) {
  53151. return null;
  53152. }
  53153. if (asString) {
  53154. var tagsArray = [];
  53155. for (var tag in obj._tags) {
  53156. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  53157. tagsArray.push(tag);
  53158. }
  53159. }
  53160. return tagsArray.join(" ");
  53161. }
  53162. else {
  53163. return obj._tags;
  53164. }
  53165. };
  53166. // the tags 'true' and 'false' are reserved and cannot be used as tags
  53167. // a tag cannot start with '||', '&&', and '!'
  53168. // it cannot contain whitespaces
  53169. Tags.AddTagsTo = function (obj, tagsString) {
  53170. if (!tagsString) {
  53171. return;
  53172. }
  53173. if (typeof tagsString !== "string") {
  53174. return;
  53175. }
  53176. var tags = tagsString.split(" ");
  53177. tags.forEach(function (tag, index, array) {
  53178. Tags._AddTagTo(obj, tag);
  53179. });
  53180. };
  53181. Tags._AddTagTo = function (obj, tag) {
  53182. tag = tag.trim();
  53183. if (tag === "" || tag === "true" || tag === "false") {
  53184. return;
  53185. }
  53186. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  53187. return;
  53188. }
  53189. Tags.EnableFor(obj);
  53190. obj._tags[tag] = true;
  53191. };
  53192. Tags.RemoveTagsFrom = function (obj, tagsString) {
  53193. if (!Tags.HasTags(obj)) {
  53194. return;
  53195. }
  53196. var tags = tagsString.split(" ");
  53197. for (var t in tags) {
  53198. Tags._RemoveTagFrom(obj, tags[t]);
  53199. }
  53200. };
  53201. Tags._RemoveTagFrom = function (obj, tag) {
  53202. delete obj._tags[tag];
  53203. };
  53204. Tags.MatchesQuery = function (obj, tagsQuery) {
  53205. if (tagsQuery === undefined) {
  53206. return true;
  53207. }
  53208. if (tagsQuery === "") {
  53209. return Tags.HasTags(obj);
  53210. }
  53211. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  53212. };
  53213. return Tags;
  53214. }());
  53215. BABYLON.Tags = Tags;
  53216. })(BABYLON || (BABYLON = {}));
  53217. //# sourceMappingURL=babylon.tags.js.map
  53218. var BABYLON;
  53219. (function (BABYLON) {
  53220. var Internals;
  53221. (function (Internals) {
  53222. var AndOrNotEvaluator = /** @class */ (function () {
  53223. function AndOrNotEvaluator() {
  53224. }
  53225. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  53226. if (!query.match(/\([^\(\)]*\)/g)) {
  53227. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  53228. }
  53229. else {
  53230. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  53231. // remove parenthesis
  53232. r = r.slice(1, r.length - 1);
  53233. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  53234. });
  53235. }
  53236. if (query === "true") {
  53237. return true;
  53238. }
  53239. if (query === "false") {
  53240. return false;
  53241. }
  53242. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  53243. };
  53244. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  53245. evaluateCallback = evaluateCallback || (function (r) {
  53246. return r === "true" ? true : false;
  53247. });
  53248. var result;
  53249. var or = parenthesisContent.split("||");
  53250. for (var i in or) {
  53251. if (or.hasOwnProperty(i)) {
  53252. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  53253. var and = ori.split("&&");
  53254. if (and.length > 1) {
  53255. for (var j = 0; j < and.length; ++j) {
  53256. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  53257. if (andj !== "true" && andj !== "false") {
  53258. if (andj[0] === "!") {
  53259. result = !evaluateCallback(andj.substring(1));
  53260. }
  53261. else {
  53262. result = evaluateCallback(andj);
  53263. }
  53264. }
  53265. else {
  53266. result = andj === "true" ? true : false;
  53267. }
  53268. if (!result) {
  53269. ori = "false";
  53270. break;
  53271. }
  53272. }
  53273. }
  53274. if (result || ori === "true") {
  53275. result = true;
  53276. break;
  53277. }
  53278. // result equals false (or undefined)
  53279. if (ori !== "true" && ori !== "false") {
  53280. if (ori[0] === "!") {
  53281. result = !evaluateCallback(ori.substring(1));
  53282. }
  53283. else {
  53284. result = evaluateCallback(ori);
  53285. }
  53286. }
  53287. else {
  53288. result = ori === "true" ? true : false;
  53289. }
  53290. }
  53291. }
  53292. // the whole parenthesis scope is replaced by 'true' or 'false'
  53293. return result ? "true" : "false";
  53294. };
  53295. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  53296. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  53297. // remove whitespaces
  53298. r = r.replace(/[\s]/g, function () { return ""; });
  53299. return r.length % 2 ? "!" : "";
  53300. });
  53301. booleanString = booleanString.trim();
  53302. if (booleanString === "!true") {
  53303. booleanString = "false";
  53304. }
  53305. else if (booleanString === "!false") {
  53306. booleanString = "true";
  53307. }
  53308. return booleanString;
  53309. };
  53310. return AndOrNotEvaluator;
  53311. }());
  53312. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  53313. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53314. })(BABYLON || (BABYLON = {}));
  53315. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  53316. var BABYLON;
  53317. (function (BABYLON) {
  53318. var Database = /** @class */ (function () {
  53319. function Database(urlToScene, callbackManifestChecked) {
  53320. // Handling various flavors of prefixed version of IndexedDB
  53321. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  53322. this.callbackManifestChecked = callbackManifestChecked;
  53323. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  53324. this.db = null;
  53325. this._enableSceneOffline = false;
  53326. this._enableTexturesOffline = false;
  53327. this.manifestVersionFound = 0;
  53328. this.mustUpdateRessources = false;
  53329. this.hasReachedQuota = false;
  53330. if (!Database.IDBStorageEnabled) {
  53331. this.callbackManifestChecked(true);
  53332. }
  53333. else {
  53334. this.checkManifestFile();
  53335. }
  53336. }
  53337. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  53338. get: function () {
  53339. return this._enableSceneOffline;
  53340. },
  53341. enumerable: true,
  53342. configurable: true
  53343. });
  53344. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  53345. get: function () {
  53346. return this._enableTexturesOffline;
  53347. },
  53348. enumerable: true,
  53349. configurable: true
  53350. });
  53351. Database.prototype.checkManifestFile = function () {
  53352. var _this = this;
  53353. var noManifestFile = function () {
  53354. _this._enableSceneOffline = false;
  53355. _this._enableTexturesOffline = false;
  53356. _this.callbackManifestChecked(false);
  53357. };
  53358. var timeStampUsed = false;
  53359. var manifestURL = this.currentSceneUrl + ".manifest";
  53360. var xhr = new XMLHttpRequest();
  53361. if (navigator.onLine) {
  53362. // Adding a timestamp to by-pass browsers' cache
  53363. timeStampUsed = true;
  53364. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  53365. }
  53366. xhr.open("GET", manifestURL, true);
  53367. xhr.addEventListener("load", function () {
  53368. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53369. try {
  53370. var manifestFile = JSON.parse(xhr.response);
  53371. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  53372. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  53373. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  53374. _this.manifestVersionFound = manifestFile.version;
  53375. }
  53376. if (_this.callbackManifestChecked) {
  53377. _this.callbackManifestChecked(true);
  53378. }
  53379. }
  53380. catch (ex) {
  53381. noManifestFile();
  53382. }
  53383. }
  53384. else {
  53385. noManifestFile();
  53386. }
  53387. }, false);
  53388. xhr.addEventListener("error", function (event) {
  53389. if (timeStampUsed) {
  53390. timeStampUsed = false;
  53391. // Let's retry without the timeStamp
  53392. // It could fail when coupled with HTML5 Offline API
  53393. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  53394. xhr.open("GET", retryManifestURL, true);
  53395. xhr.send();
  53396. }
  53397. else {
  53398. noManifestFile();
  53399. }
  53400. }, false);
  53401. try {
  53402. xhr.send();
  53403. }
  53404. catch (ex) {
  53405. BABYLON.Tools.Error("Error on XHR send request.");
  53406. this.callbackManifestChecked(false);
  53407. }
  53408. };
  53409. Database.prototype.openAsync = function (successCallback, errorCallback) {
  53410. var _this = this;
  53411. var handleError = function () {
  53412. _this.isSupported = false;
  53413. if (errorCallback)
  53414. errorCallback();
  53415. };
  53416. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  53417. // Your browser doesn't support IndexedDB
  53418. this.isSupported = false;
  53419. if (errorCallback)
  53420. errorCallback();
  53421. }
  53422. else {
  53423. // If the DB hasn't been opened or created yet
  53424. if (!this.db) {
  53425. this.hasReachedQuota = false;
  53426. this.isSupported = true;
  53427. var request = this.idbFactory.open("babylonjs", 1);
  53428. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  53429. request.onerror = function (event) {
  53430. handleError();
  53431. };
  53432. // executes when a version change transaction cannot complete due to other active transactions
  53433. request.onblocked = function (event) {
  53434. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  53435. handleError();
  53436. };
  53437. // DB has been opened successfully
  53438. request.onsuccess = function (event) {
  53439. _this.db = request.result;
  53440. successCallback();
  53441. };
  53442. // Initialization of the DB. Creating Scenes & Textures stores
  53443. request.onupgradeneeded = function (event) {
  53444. _this.db = (event.target).result;
  53445. if (_this.db) {
  53446. try {
  53447. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  53448. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  53449. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  53450. }
  53451. catch (ex) {
  53452. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  53453. handleError();
  53454. }
  53455. }
  53456. };
  53457. }
  53458. else {
  53459. if (successCallback)
  53460. successCallback();
  53461. }
  53462. }
  53463. };
  53464. Database.prototype.loadImageFromDB = function (url, image) {
  53465. var _this = this;
  53466. var completeURL = Database.ReturnFullUrlLocation(url);
  53467. var saveAndLoadImage = function () {
  53468. if (!_this.hasReachedQuota && _this.db !== null) {
  53469. // the texture is not yet in the DB, let's try to save it
  53470. _this._saveImageIntoDBAsync(completeURL, image);
  53471. }
  53472. else {
  53473. image.src = url;
  53474. }
  53475. };
  53476. if (!this.mustUpdateRessources) {
  53477. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  53478. }
  53479. else {
  53480. saveAndLoadImage();
  53481. }
  53482. };
  53483. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  53484. if (this.isSupported && this.db !== null) {
  53485. var texture;
  53486. var transaction = this.db.transaction(["textures"]);
  53487. transaction.onabort = function (event) {
  53488. image.src = url;
  53489. };
  53490. transaction.oncomplete = function (event) {
  53491. var blobTextureURL;
  53492. if (texture) {
  53493. var URL = window.URL || window.webkitURL;
  53494. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  53495. image.onerror = function () {
  53496. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  53497. image.src = url;
  53498. };
  53499. image.src = blobTextureURL;
  53500. }
  53501. else {
  53502. notInDBCallback();
  53503. }
  53504. };
  53505. var getRequest = transaction.objectStore("textures").get(url);
  53506. getRequest.onsuccess = function (event) {
  53507. texture = (event.target).result;
  53508. };
  53509. getRequest.onerror = function (event) {
  53510. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  53511. image.src = url;
  53512. };
  53513. }
  53514. else {
  53515. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53516. image.src = url;
  53517. }
  53518. };
  53519. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  53520. var _this = this;
  53521. if (this.isSupported) {
  53522. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  53523. var generateBlobUrl = function () {
  53524. var blobTextureURL;
  53525. if (blob) {
  53526. var URL = window.URL || window.webkitURL;
  53527. try {
  53528. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  53529. }
  53530. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  53531. catch (ex) {
  53532. blobTextureURL = URL.createObjectURL(blob);
  53533. }
  53534. }
  53535. if (blobTextureURL) {
  53536. image.src = blobTextureURL;
  53537. }
  53538. };
  53539. if (Database.IsUASupportingBlobStorage) {
  53540. var xhr = new XMLHttpRequest(), blob;
  53541. xhr.open("GET", url, true);
  53542. xhr.responseType = "blob";
  53543. xhr.addEventListener("load", function () {
  53544. if (xhr.status === 200 && _this.db) {
  53545. // Blob as response (XHR2)
  53546. blob = xhr.response;
  53547. var transaction = _this.db.transaction(["textures"], "readwrite");
  53548. // the transaction could abort because of a QuotaExceededError error
  53549. transaction.onabort = function (event) {
  53550. try {
  53551. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53552. var srcElement = (event.srcElement || event.target);
  53553. var error = srcElement.error;
  53554. if (error && error.name === "QuotaExceededError") {
  53555. _this.hasReachedQuota = true;
  53556. }
  53557. }
  53558. catch (ex) { }
  53559. generateBlobUrl();
  53560. };
  53561. transaction.oncomplete = function (event) {
  53562. generateBlobUrl();
  53563. };
  53564. var newTexture = { textureUrl: url, data: blob };
  53565. try {
  53566. // Put the blob into the dabase
  53567. var addRequest = transaction.objectStore("textures").put(newTexture);
  53568. addRequest.onsuccess = function (event) {
  53569. };
  53570. addRequest.onerror = function (event) {
  53571. generateBlobUrl();
  53572. };
  53573. }
  53574. catch (ex) {
  53575. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  53576. if (ex.code === 25) {
  53577. Database.IsUASupportingBlobStorage = false;
  53578. }
  53579. image.src = url;
  53580. }
  53581. }
  53582. else {
  53583. image.src = url;
  53584. }
  53585. }, false);
  53586. xhr.addEventListener("error", function (event) {
  53587. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  53588. image.src = url;
  53589. }, false);
  53590. xhr.send();
  53591. }
  53592. else {
  53593. image.src = url;
  53594. }
  53595. }
  53596. else {
  53597. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53598. image.src = url;
  53599. }
  53600. };
  53601. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  53602. var _this = this;
  53603. var updateVersion = function () {
  53604. // the version is not yet in the DB or we need to update it
  53605. _this._saveVersionIntoDBAsync(url, versionLoaded);
  53606. };
  53607. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  53608. };
  53609. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  53610. var _this = this;
  53611. if (this.isSupported && this.db) {
  53612. var version;
  53613. try {
  53614. var transaction = this.db.transaction(["versions"]);
  53615. transaction.oncomplete = function (event) {
  53616. if (version) {
  53617. // If the version in the JSON file is > than the version in DB
  53618. if (_this.manifestVersionFound > version.data) {
  53619. _this.mustUpdateRessources = true;
  53620. updateInDBCallback();
  53621. }
  53622. else {
  53623. callback(version.data);
  53624. }
  53625. }
  53626. else {
  53627. _this.mustUpdateRessources = true;
  53628. updateInDBCallback();
  53629. }
  53630. };
  53631. transaction.onabort = function (event) {
  53632. callback(-1);
  53633. };
  53634. var getRequest = transaction.objectStore("versions").get(url);
  53635. getRequest.onsuccess = function (event) {
  53636. version = (event.target).result;
  53637. };
  53638. getRequest.onerror = function (event) {
  53639. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  53640. callback(-1);
  53641. };
  53642. }
  53643. catch (ex) {
  53644. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  53645. callback(-1);
  53646. }
  53647. }
  53648. else {
  53649. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53650. callback(-1);
  53651. }
  53652. };
  53653. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  53654. var _this = this;
  53655. if (this.isSupported && !this.hasReachedQuota && this.db) {
  53656. try {
  53657. // Open a transaction to the database
  53658. var transaction = this.db.transaction(["versions"], "readwrite");
  53659. // the transaction could abort because of a QuotaExceededError error
  53660. transaction.onabort = function (event) {
  53661. try {
  53662. var error = event.srcElement['error'];
  53663. if (error && error.name === "QuotaExceededError") {
  53664. _this.hasReachedQuota = true;
  53665. }
  53666. }
  53667. catch (ex) { }
  53668. callback(-1);
  53669. };
  53670. transaction.oncomplete = function (event) {
  53671. callback(_this.manifestVersionFound);
  53672. };
  53673. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  53674. // Put the scene into the database
  53675. var addRequest = transaction.objectStore("versions").put(newVersion);
  53676. addRequest.onsuccess = function (event) {
  53677. };
  53678. addRequest.onerror = function (event) {
  53679. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  53680. };
  53681. }
  53682. catch (ex) {
  53683. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  53684. callback(-1);
  53685. }
  53686. }
  53687. else {
  53688. callback(-1);
  53689. }
  53690. };
  53691. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  53692. var _this = this;
  53693. var completeUrl = Database.ReturnFullUrlLocation(url);
  53694. var saveAndLoadFile = function () {
  53695. // the scene is not yet in the DB, let's try to save it
  53696. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  53697. };
  53698. this._checkVersionFromDB(completeUrl, function (version) {
  53699. if (version !== -1) {
  53700. if (!_this.mustUpdateRessources) {
  53701. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  53702. }
  53703. else {
  53704. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  53705. }
  53706. }
  53707. else {
  53708. if (errorCallback) {
  53709. errorCallback();
  53710. }
  53711. }
  53712. });
  53713. };
  53714. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  53715. if (this.isSupported && this.db) {
  53716. var targetStore;
  53717. if (url.indexOf(".babylon") !== -1) {
  53718. targetStore = "scenes";
  53719. }
  53720. else {
  53721. targetStore = "textures";
  53722. }
  53723. var file;
  53724. var transaction = this.db.transaction([targetStore]);
  53725. transaction.oncomplete = function (event) {
  53726. if (file) {
  53727. callback(file.data);
  53728. }
  53729. else {
  53730. notInDBCallback();
  53731. }
  53732. };
  53733. transaction.onabort = function (event) {
  53734. notInDBCallback();
  53735. };
  53736. var getRequest = transaction.objectStore(targetStore).get(url);
  53737. getRequest.onsuccess = function (event) {
  53738. file = (event.target).result;
  53739. };
  53740. getRequest.onerror = function (event) {
  53741. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  53742. notInDBCallback();
  53743. };
  53744. }
  53745. else {
  53746. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53747. callback();
  53748. }
  53749. };
  53750. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  53751. var _this = this;
  53752. if (this.isSupported) {
  53753. var targetStore;
  53754. if (url.indexOf(".babylon") !== -1) {
  53755. targetStore = "scenes";
  53756. }
  53757. else {
  53758. targetStore = "textures";
  53759. }
  53760. // Create XHR
  53761. var xhr = new XMLHttpRequest();
  53762. var fileData;
  53763. xhr.open("GET", url, true);
  53764. if (useArrayBuffer) {
  53765. xhr.responseType = "arraybuffer";
  53766. }
  53767. if (progressCallback) {
  53768. xhr.onprogress = progressCallback;
  53769. }
  53770. xhr.addEventListener("load", function () {
  53771. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  53772. // Blob as response (XHR2)
  53773. //fileData = xhr.responseText;
  53774. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  53775. if (!_this.hasReachedQuota && _this.db) {
  53776. // Open a transaction to the database
  53777. var transaction = _this.db.transaction([targetStore], "readwrite");
  53778. // the transaction could abort because of a QuotaExceededError error
  53779. transaction.onabort = function (event) {
  53780. try {
  53781. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53782. var error = event.srcElement['error'];
  53783. if (error && error.name === "QuotaExceededError") {
  53784. _this.hasReachedQuota = true;
  53785. }
  53786. }
  53787. catch (ex) { }
  53788. callback(fileData);
  53789. };
  53790. transaction.oncomplete = function (event) {
  53791. callback(fileData);
  53792. };
  53793. var newFile;
  53794. if (targetStore === "scenes") {
  53795. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  53796. }
  53797. else {
  53798. newFile = { textureUrl: url, data: fileData };
  53799. }
  53800. try {
  53801. // Put the scene into the database
  53802. var addRequest = transaction.objectStore(targetStore).put(newFile);
  53803. addRequest.onsuccess = function (event) {
  53804. };
  53805. addRequest.onerror = function (event) {
  53806. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  53807. };
  53808. }
  53809. catch (ex) {
  53810. callback(fileData);
  53811. }
  53812. }
  53813. else {
  53814. callback(fileData);
  53815. }
  53816. }
  53817. else {
  53818. callback();
  53819. }
  53820. }, false);
  53821. xhr.addEventListener("error", function (event) {
  53822. BABYLON.Tools.Error("error on XHR request.");
  53823. callback();
  53824. }, false);
  53825. xhr.send();
  53826. }
  53827. else {
  53828. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53829. callback();
  53830. }
  53831. };
  53832. Database.IsUASupportingBlobStorage = true;
  53833. Database.IDBStorageEnabled = true;
  53834. Database.parseURL = function (url) {
  53835. var a = document.createElement('a');
  53836. a.href = url;
  53837. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  53838. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  53839. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  53840. return absLocation;
  53841. };
  53842. Database.ReturnFullUrlLocation = function (url) {
  53843. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  53844. return (Database.parseURL(window.location.href) + url);
  53845. }
  53846. else {
  53847. return url;
  53848. }
  53849. };
  53850. return Database;
  53851. }());
  53852. BABYLON.Database = Database;
  53853. })(BABYLON || (BABYLON = {}));
  53854. //# sourceMappingURL=babylon.database.js.map
  53855. var BABYLON;
  53856. (function (BABYLON) {
  53857. var FresnelParameters = /** @class */ (function () {
  53858. function FresnelParameters() {
  53859. this._isEnabled = true;
  53860. this.leftColor = BABYLON.Color3.White();
  53861. this.rightColor = BABYLON.Color3.Black();
  53862. this.bias = 0;
  53863. this.power = 1;
  53864. }
  53865. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  53866. get: function () {
  53867. return this._isEnabled;
  53868. },
  53869. set: function (value) {
  53870. if (this._isEnabled === value) {
  53871. return;
  53872. }
  53873. this._isEnabled = value;
  53874. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  53875. },
  53876. enumerable: true,
  53877. configurable: true
  53878. });
  53879. FresnelParameters.prototype.clone = function () {
  53880. var newFresnelParameters = new FresnelParameters();
  53881. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  53882. return newFresnelParameters;
  53883. };
  53884. FresnelParameters.prototype.serialize = function () {
  53885. var serializationObject = {};
  53886. serializationObject.isEnabled = this.isEnabled;
  53887. serializationObject.leftColor = this.leftColor;
  53888. serializationObject.rightColor = this.rightColor;
  53889. serializationObject.bias = this.bias;
  53890. serializationObject.power = this.power;
  53891. return serializationObject;
  53892. };
  53893. FresnelParameters.Parse = function (parsedFresnelParameters) {
  53894. var fresnelParameters = new FresnelParameters();
  53895. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  53896. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  53897. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  53898. fresnelParameters.bias = parsedFresnelParameters.bias;
  53899. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  53900. return fresnelParameters;
  53901. };
  53902. return FresnelParameters;
  53903. }());
  53904. BABYLON.FresnelParameters = FresnelParameters;
  53905. })(BABYLON || (BABYLON = {}));
  53906. //# sourceMappingURL=babylon.fresnelParameters.js.map
  53907. var BABYLON;
  53908. (function (BABYLON) {
  53909. var MultiMaterial = /** @class */ (function (_super) {
  53910. __extends(MultiMaterial, _super);
  53911. function MultiMaterial(name, scene) {
  53912. var _this = _super.call(this, name, scene, true) || this;
  53913. scene.multiMaterials.push(_this);
  53914. _this.subMaterials = new Array();
  53915. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  53916. return _this;
  53917. }
  53918. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  53919. get: function () {
  53920. return this._subMaterials;
  53921. },
  53922. set: function (value) {
  53923. this._subMaterials = value;
  53924. this._hookArray(value);
  53925. },
  53926. enumerable: true,
  53927. configurable: true
  53928. });
  53929. MultiMaterial.prototype._hookArray = function (array) {
  53930. var _this = this;
  53931. var oldPush = array.push;
  53932. array.push = function () {
  53933. var items = [];
  53934. for (var _i = 0; _i < arguments.length; _i++) {
  53935. items[_i] = arguments[_i];
  53936. }
  53937. var result = oldPush.apply(array, items);
  53938. _this._markAllSubMeshesAsTexturesDirty();
  53939. return result;
  53940. };
  53941. var oldSplice = array.splice;
  53942. array.splice = function (index, deleteCount) {
  53943. var deleted = oldSplice.apply(array, [index, deleteCount]);
  53944. _this._markAllSubMeshesAsTexturesDirty();
  53945. return deleted;
  53946. };
  53947. };
  53948. // Properties
  53949. MultiMaterial.prototype.getSubMaterial = function (index) {
  53950. if (index < 0 || index >= this.subMaterials.length) {
  53951. return this.getScene().defaultMaterial;
  53952. }
  53953. return this.subMaterials[index];
  53954. };
  53955. MultiMaterial.prototype.getActiveTextures = function () {
  53956. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  53957. if (subMaterial) {
  53958. return subMaterial.getActiveTextures();
  53959. }
  53960. else {
  53961. return [];
  53962. }
  53963. }));
  53964. var _a;
  53965. };
  53966. // Methods
  53967. MultiMaterial.prototype.getClassName = function () {
  53968. return "MultiMaterial";
  53969. };
  53970. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  53971. for (var index = 0; index < this.subMaterials.length; index++) {
  53972. var subMaterial = this.subMaterials[index];
  53973. if (subMaterial) {
  53974. if (subMaterial.storeEffectOnSubMeshes) {
  53975. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  53976. return false;
  53977. }
  53978. continue;
  53979. }
  53980. if (!subMaterial.isReady(mesh)) {
  53981. return false;
  53982. }
  53983. }
  53984. }
  53985. return true;
  53986. };
  53987. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  53988. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  53989. for (var index = 0; index < this.subMaterials.length; index++) {
  53990. var subMaterial = null;
  53991. var current = this.subMaterials[index];
  53992. if (cloneChildren && current) {
  53993. subMaterial = current.clone(name + "-" + current.name);
  53994. }
  53995. else {
  53996. subMaterial = this.subMaterials[index];
  53997. }
  53998. newMultiMaterial.subMaterials.push(subMaterial);
  53999. }
  54000. return newMultiMaterial;
  54001. };
  54002. MultiMaterial.prototype.serialize = function () {
  54003. var serializationObject = {};
  54004. serializationObject.name = this.name;
  54005. serializationObject.id = this.id;
  54006. serializationObject.tags = BABYLON.Tags.GetTags(this);
  54007. serializationObject.materials = [];
  54008. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  54009. var subMat = this.subMaterials[matIndex];
  54010. if (subMat) {
  54011. serializationObject.materials.push(subMat.id);
  54012. }
  54013. else {
  54014. serializationObject.materials.push(null);
  54015. }
  54016. }
  54017. return serializationObject;
  54018. };
  54019. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54020. var scene = this.getScene();
  54021. if (!scene) {
  54022. return;
  54023. }
  54024. var index = scene.multiMaterials.indexOf(this);
  54025. if (index >= 0) {
  54026. scene.multiMaterials.splice(index, 1);
  54027. }
  54028. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54029. };
  54030. return MultiMaterial;
  54031. }(BABYLON.Material));
  54032. BABYLON.MultiMaterial = MultiMaterial;
  54033. })(BABYLON || (BABYLON = {}));
  54034. //# sourceMappingURL=babylon.multiMaterial.js.map
  54035. var BABYLON;
  54036. (function (BABYLON) {
  54037. var FreeCameraTouchInput = /** @class */ (function () {
  54038. function FreeCameraTouchInput() {
  54039. this._offsetX = null;
  54040. this._offsetY = null;
  54041. this._pointerCount = 0;
  54042. this._pointerPressed = new Array();
  54043. this.touchAngularSensibility = 200000.0;
  54044. this.touchMoveSensibility = 250.0;
  54045. }
  54046. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  54047. var _this = this;
  54048. var previousPosition = null;
  54049. if (this._pointerInput === undefined) {
  54050. this._onLostFocus = function (evt) {
  54051. _this._offsetX = null;
  54052. _this._offsetY = null;
  54053. };
  54054. this._pointerInput = function (p, s) {
  54055. var evt = p.event;
  54056. if (evt.pointerType === "mouse") {
  54057. return;
  54058. }
  54059. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  54060. if (!noPreventDefault) {
  54061. evt.preventDefault();
  54062. }
  54063. _this._pointerPressed.push(evt.pointerId);
  54064. if (_this._pointerPressed.length !== 1) {
  54065. return;
  54066. }
  54067. previousPosition = {
  54068. x: evt.clientX,
  54069. y: evt.clientY
  54070. };
  54071. }
  54072. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  54073. if (!noPreventDefault) {
  54074. evt.preventDefault();
  54075. }
  54076. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54077. if (index === -1) {
  54078. return;
  54079. }
  54080. _this._pointerPressed.splice(index, 1);
  54081. if (index != 0) {
  54082. return;
  54083. }
  54084. previousPosition = null;
  54085. _this._offsetX = null;
  54086. _this._offsetY = null;
  54087. }
  54088. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  54089. if (!noPreventDefault) {
  54090. evt.preventDefault();
  54091. }
  54092. if (!previousPosition) {
  54093. return;
  54094. }
  54095. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54096. if (index != 0) {
  54097. return;
  54098. }
  54099. _this._offsetX = evt.clientX - previousPosition.x;
  54100. _this._offsetY = -(evt.clientY - previousPosition.y);
  54101. }
  54102. };
  54103. }
  54104. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  54105. if (this._onLostFocus) {
  54106. element.addEventListener("blur", this._onLostFocus);
  54107. }
  54108. };
  54109. FreeCameraTouchInput.prototype.detachControl = function (element) {
  54110. if (this._pointerInput && element) {
  54111. if (this._observer) {
  54112. this.camera.getScene().onPointerObservable.remove(this._observer);
  54113. this._observer = null;
  54114. }
  54115. if (this._onLostFocus) {
  54116. element.removeEventListener("blur", this._onLostFocus);
  54117. this._onLostFocus = null;
  54118. }
  54119. this._pointerPressed = [];
  54120. this._offsetX = null;
  54121. this._offsetY = null;
  54122. this._pointerCount = 0;
  54123. }
  54124. };
  54125. FreeCameraTouchInput.prototype.checkInputs = function () {
  54126. if (this._offsetX && this._offsetY) {
  54127. var camera = this.camera;
  54128. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  54129. if (this._pointerPressed.length > 1) {
  54130. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  54131. }
  54132. else {
  54133. var speed = camera._computeLocalCameraSpeed();
  54134. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  54135. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  54136. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  54137. }
  54138. }
  54139. };
  54140. FreeCameraTouchInput.prototype.getClassName = function () {
  54141. return "FreeCameraTouchInput";
  54142. };
  54143. FreeCameraTouchInput.prototype.getSimpleName = function () {
  54144. return "touch";
  54145. };
  54146. __decorate([
  54147. BABYLON.serialize()
  54148. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  54149. __decorate([
  54150. BABYLON.serialize()
  54151. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  54152. return FreeCameraTouchInput;
  54153. }());
  54154. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  54155. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  54156. })(BABYLON || (BABYLON = {}));
  54157. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  54158. var BABYLON;
  54159. (function (BABYLON) {
  54160. // We're mainly based on the logic defined into the FreeCamera code
  54161. var TouchCamera = /** @class */ (function (_super) {
  54162. __extends(TouchCamera, _super);
  54163. //-- end properties for backward compatibility for inputs
  54164. function TouchCamera(name, position, scene) {
  54165. var _this = _super.call(this, name, position, scene) || this;
  54166. _this.inputs.addTouch();
  54167. _this._setupInputs();
  54168. return _this;
  54169. }
  54170. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  54171. //-- Begin properties for backward compatibility for inputs
  54172. get: function () {
  54173. var touch = this.inputs.attached["touch"];
  54174. if (touch)
  54175. return touch.touchAngularSensibility;
  54176. return 0;
  54177. },
  54178. set: function (value) {
  54179. var touch = this.inputs.attached["touch"];
  54180. if (touch)
  54181. touch.touchAngularSensibility = value;
  54182. },
  54183. enumerable: true,
  54184. configurable: true
  54185. });
  54186. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  54187. get: function () {
  54188. var touch = this.inputs.attached["touch"];
  54189. if (touch)
  54190. return touch.touchMoveSensibility;
  54191. return 0;
  54192. },
  54193. set: function (value) {
  54194. var touch = this.inputs.attached["touch"];
  54195. if (touch)
  54196. touch.touchMoveSensibility = value;
  54197. },
  54198. enumerable: true,
  54199. configurable: true
  54200. });
  54201. TouchCamera.prototype.getClassName = function () {
  54202. return "TouchCamera";
  54203. };
  54204. TouchCamera.prototype._setupInputs = function () {
  54205. var mouse = this.inputs.attached["mouse"];
  54206. if (mouse) {
  54207. mouse.touchEnabled = false;
  54208. }
  54209. };
  54210. return TouchCamera;
  54211. }(BABYLON.FreeCamera));
  54212. BABYLON.TouchCamera = TouchCamera;
  54213. })(BABYLON || (BABYLON = {}));
  54214. //# sourceMappingURL=babylon.touchCamera.js.map
  54215. var BABYLON;
  54216. (function (BABYLON) {
  54217. var ProceduralTexture = /** @class */ (function (_super) {
  54218. __extends(ProceduralTexture, _super);
  54219. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  54220. if (fallbackTexture === void 0) { fallbackTexture = null; }
  54221. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54222. if (isCube === void 0) { isCube = false; }
  54223. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54224. _this.isCube = isCube;
  54225. _this.isEnabled = true;
  54226. _this._currentRefreshId = -1;
  54227. _this._refreshRate = 1;
  54228. _this._vertexBuffers = {};
  54229. _this._uniforms = new Array();
  54230. _this._samplers = new Array();
  54231. _this._textures = {};
  54232. _this._floats = {};
  54233. _this._floatsArrays = {};
  54234. _this._colors3 = {};
  54235. _this._colors4 = {};
  54236. _this._vectors2 = {};
  54237. _this._vectors3 = {};
  54238. _this._matrices = {};
  54239. _this._fallbackTextureUsed = false;
  54240. scene._proceduralTextures.push(_this);
  54241. _this._engine = scene.getEngine();
  54242. _this.name = name;
  54243. _this.isRenderTarget = true;
  54244. _this._size = size;
  54245. _this._generateMipMaps = generateMipMaps;
  54246. _this.setFragment(fragment);
  54247. _this._fallbackTexture = fallbackTexture;
  54248. if (isCube) {
  54249. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  54250. _this.setFloat("face", 0);
  54251. }
  54252. else {
  54253. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  54254. }
  54255. // VBO
  54256. var vertices = [];
  54257. vertices.push(1, 1);
  54258. vertices.push(-1, 1);
  54259. vertices.push(-1, -1);
  54260. vertices.push(1, -1);
  54261. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54262. _this._createIndexBuffer();
  54263. return _this;
  54264. }
  54265. ProceduralTexture.prototype._createIndexBuffer = function () {
  54266. var engine = this._engine;
  54267. // Indices
  54268. var indices = [];
  54269. indices.push(0);
  54270. indices.push(1);
  54271. indices.push(2);
  54272. indices.push(0);
  54273. indices.push(2);
  54274. indices.push(3);
  54275. this._indexBuffer = engine.createIndexBuffer(indices);
  54276. };
  54277. ProceduralTexture.prototype._rebuild = function () {
  54278. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54279. if (vb) {
  54280. vb._rebuild();
  54281. }
  54282. this._createIndexBuffer();
  54283. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54284. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54285. }
  54286. };
  54287. ProceduralTexture.prototype.reset = function () {
  54288. if (this._effect === undefined) {
  54289. return;
  54290. }
  54291. var engine = this._engine;
  54292. engine._releaseEffect(this._effect);
  54293. };
  54294. ProceduralTexture.prototype.isReady = function () {
  54295. var _this = this;
  54296. var engine = this._engine;
  54297. var shaders;
  54298. if (!this._fragment) {
  54299. return false;
  54300. }
  54301. if (this._fallbackTextureUsed) {
  54302. return true;
  54303. }
  54304. if (this._fragment.fragmentElement !== undefined) {
  54305. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  54306. }
  54307. else {
  54308. shaders = { vertex: "procedural", fragment: this._fragment };
  54309. }
  54310. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  54311. _this.releaseInternalTexture();
  54312. if (_this._fallbackTexture) {
  54313. _this._texture = _this._fallbackTexture._texture;
  54314. if (_this._texture) {
  54315. _this._texture.incrementReferences();
  54316. }
  54317. }
  54318. _this._fallbackTextureUsed = true;
  54319. });
  54320. return this._effect.isReady();
  54321. };
  54322. ProceduralTexture.prototype.resetRefreshCounter = function () {
  54323. this._currentRefreshId = -1;
  54324. };
  54325. ProceduralTexture.prototype.setFragment = function (fragment) {
  54326. this._fragment = fragment;
  54327. };
  54328. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  54329. get: function () {
  54330. return this._refreshRate;
  54331. },
  54332. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54333. set: function (value) {
  54334. this._refreshRate = value;
  54335. this.resetRefreshCounter();
  54336. },
  54337. enumerable: true,
  54338. configurable: true
  54339. });
  54340. ProceduralTexture.prototype._shouldRender = function () {
  54341. if (!this.isEnabled || !this.isReady() || !this._texture) {
  54342. return false;
  54343. }
  54344. if (this._fallbackTextureUsed) {
  54345. return false;
  54346. }
  54347. if (this._currentRefreshId === -1) {
  54348. this._currentRefreshId = 1;
  54349. return true;
  54350. }
  54351. if (this.refreshRate === this._currentRefreshId) {
  54352. this._currentRefreshId = 1;
  54353. return true;
  54354. }
  54355. this._currentRefreshId++;
  54356. return false;
  54357. };
  54358. ProceduralTexture.prototype.getRenderSize = function () {
  54359. return this._size;
  54360. };
  54361. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  54362. if (this._fallbackTextureUsed) {
  54363. return;
  54364. }
  54365. this.releaseInternalTexture();
  54366. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  54367. };
  54368. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  54369. if (this._uniforms.indexOf(uniformName) === -1) {
  54370. this._uniforms.push(uniformName);
  54371. }
  54372. };
  54373. ProceduralTexture.prototype.setTexture = function (name, texture) {
  54374. if (this._samplers.indexOf(name) === -1) {
  54375. this._samplers.push(name);
  54376. }
  54377. this._textures[name] = texture;
  54378. return this;
  54379. };
  54380. ProceduralTexture.prototype.setFloat = function (name, value) {
  54381. this._checkUniform(name);
  54382. this._floats[name] = value;
  54383. return this;
  54384. };
  54385. ProceduralTexture.prototype.setFloats = function (name, value) {
  54386. this._checkUniform(name);
  54387. this._floatsArrays[name] = value;
  54388. return this;
  54389. };
  54390. ProceduralTexture.prototype.setColor3 = function (name, value) {
  54391. this._checkUniform(name);
  54392. this._colors3[name] = value;
  54393. return this;
  54394. };
  54395. ProceduralTexture.prototype.setColor4 = function (name, value) {
  54396. this._checkUniform(name);
  54397. this._colors4[name] = value;
  54398. return this;
  54399. };
  54400. ProceduralTexture.prototype.setVector2 = function (name, value) {
  54401. this._checkUniform(name);
  54402. this._vectors2[name] = value;
  54403. return this;
  54404. };
  54405. ProceduralTexture.prototype.setVector3 = function (name, value) {
  54406. this._checkUniform(name);
  54407. this._vectors3[name] = value;
  54408. return this;
  54409. };
  54410. ProceduralTexture.prototype.setMatrix = function (name, value) {
  54411. this._checkUniform(name);
  54412. this._matrices[name] = value;
  54413. return this;
  54414. };
  54415. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54416. var scene = this.getScene();
  54417. if (!scene) {
  54418. return;
  54419. }
  54420. var engine = this._engine;
  54421. // Render
  54422. engine.enableEffect(this._effect);
  54423. engine.setState(false);
  54424. // Texture
  54425. for (var name in this._textures) {
  54426. this._effect.setTexture(name, this._textures[name]);
  54427. }
  54428. // Float
  54429. for (name in this._floats) {
  54430. this._effect.setFloat(name, this._floats[name]);
  54431. }
  54432. // Floats
  54433. for (name in this._floatsArrays) {
  54434. this._effect.setArray(name, this._floatsArrays[name]);
  54435. }
  54436. // Color3
  54437. for (name in this._colors3) {
  54438. this._effect.setColor3(name, this._colors3[name]);
  54439. }
  54440. // Color4
  54441. for (name in this._colors4) {
  54442. var color = this._colors4[name];
  54443. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54444. }
  54445. // Vector2
  54446. for (name in this._vectors2) {
  54447. this._effect.setVector2(name, this._vectors2[name]);
  54448. }
  54449. // Vector3
  54450. for (name in this._vectors3) {
  54451. this._effect.setVector3(name, this._vectors3[name]);
  54452. }
  54453. // Matrix
  54454. for (name in this._matrices) {
  54455. this._effect.setMatrix(name, this._matrices[name]);
  54456. }
  54457. if (!this._texture) {
  54458. return;
  54459. }
  54460. if (this.isCube) {
  54461. for (var face = 0; face < 6; face++) {
  54462. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  54463. // VBOs
  54464. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54465. this._effect.setFloat("face", face);
  54466. // Clear
  54467. engine.clear(scene.clearColor, true, true, true);
  54468. // Draw order
  54469. engine.draw(true, 0, 6);
  54470. // Mipmaps
  54471. if (face === 5) {
  54472. engine.generateMipMapsForCubemap(this._texture);
  54473. }
  54474. }
  54475. }
  54476. else {
  54477. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  54478. // VBOs
  54479. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54480. // Clear
  54481. engine.clear(scene.clearColor, true, true, true);
  54482. // Draw order
  54483. engine.draw(true, 0, 6);
  54484. }
  54485. // Unbind
  54486. engine.unBindFramebuffer(this._texture, this.isCube);
  54487. if (this.onGenerated) {
  54488. this.onGenerated();
  54489. }
  54490. };
  54491. ProceduralTexture.prototype.clone = function () {
  54492. var textureSize = this.getSize();
  54493. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  54494. // Base texture
  54495. newTexture.hasAlpha = this.hasAlpha;
  54496. newTexture.level = this.level;
  54497. // RenderTarget Texture
  54498. newTexture.coordinatesMode = this.coordinatesMode;
  54499. return newTexture;
  54500. };
  54501. ProceduralTexture.prototype.dispose = function () {
  54502. var scene = this.getScene();
  54503. if (!scene) {
  54504. return;
  54505. }
  54506. var index = scene._proceduralTextures.indexOf(this);
  54507. if (index >= 0) {
  54508. scene._proceduralTextures.splice(index, 1);
  54509. }
  54510. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54511. if (vertexBuffer) {
  54512. vertexBuffer.dispose();
  54513. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54514. }
  54515. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  54516. this._indexBuffer = null;
  54517. }
  54518. _super.prototype.dispose.call(this);
  54519. };
  54520. return ProceduralTexture;
  54521. }(BABYLON.Texture));
  54522. BABYLON.ProceduralTexture = ProceduralTexture;
  54523. })(BABYLON || (BABYLON = {}));
  54524. //# sourceMappingURL=babylon.proceduralTexture.js.map
  54525. var BABYLON;
  54526. (function (BABYLON) {
  54527. var CustomProceduralTexture = /** @class */ (function (_super) {
  54528. __extends(CustomProceduralTexture, _super);
  54529. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  54530. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  54531. _this._animate = true;
  54532. _this._time = 0;
  54533. _this._texturePath = texturePath;
  54534. //Try to load json
  54535. _this.loadJson(texturePath);
  54536. _this.refreshRate = 1;
  54537. return _this;
  54538. }
  54539. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  54540. var _this = this;
  54541. var noConfigFile = function () {
  54542. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  54543. try {
  54544. _this.setFragment(_this._texturePath);
  54545. }
  54546. catch (ex) {
  54547. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  54548. }
  54549. };
  54550. var configFileUrl = jsonUrl + "/config.json";
  54551. var xhr = new XMLHttpRequest();
  54552. xhr.open("GET", configFileUrl, true);
  54553. xhr.addEventListener("load", function () {
  54554. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54555. try {
  54556. _this._config = JSON.parse(xhr.response);
  54557. _this.updateShaderUniforms();
  54558. _this.updateTextures();
  54559. _this.setFragment(_this._texturePath + "/custom");
  54560. _this._animate = _this._config.animate;
  54561. _this.refreshRate = _this._config.refreshrate;
  54562. }
  54563. catch (ex) {
  54564. noConfigFile();
  54565. }
  54566. }
  54567. else {
  54568. noConfigFile();
  54569. }
  54570. }, false);
  54571. xhr.addEventListener("error", function () {
  54572. noConfigFile();
  54573. }, false);
  54574. try {
  54575. xhr.send();
  54576. }
  54577. catch (ex) {
  54578. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  54579. }
  54580. };
  54581. CustomProceduralTexture.prototype.isReady = function () {
  54582. if (!_super.prototype.isReady.call(this)) {
  54583. return false;
  54584. }
  54585. for (var name in this._textures) {
  54586. var texture = this._textures[name];
  54587. if (!texture.isReady()) {
  54588. return false;
  54589. }
  54590. }
  54591. return true;
  54592. };
  54593. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54594. var scene = this.getScene();
  54595. if (this._animate && scene) {
  54596. this._time += scene.getAnimationRatio() * 0.03;
  54597. this.updateShaderUniforms();
  54598. }
  54599. _super.prototype.render.call(this, useCameraPostProcess);
  54600. };
  54601. CustomProceduralTexture.prototype.updateTextures = function () {
  54602. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  54603. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  54604. }
  54605. };
  54606. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  54607. if (this._config) {
  54608. for (var j = 0; j < this._config.uniforms.length; j++) {
  54609. var uniform = this._config.uniforms[j];
  54610. switch (uniform.type) {
  54611. case "float":
  54612. this.setFloat(uniform.name, uniform.value);
  54613. break;
  54614. case "color3":
  54615. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  54616. break;
  54617. case "color4":
  54618. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  54619. break;
  54620. case "vector2":
  54621. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  54622. break;
  54623. case "vector3":
  54624. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  54625. break;
  54626. }
  54627. }
  54628. }
  54629. this.setFloat("time", this._time);
  54630. };
  54631. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  54632. get: function () {
  54633. return this._animate;
  54634. },
  54635. set: function (value) {
  54636. this._animate = value;
  54637. },
  54638. enumerable: true,
  54639. configurable: true
  54640. });
  54641. return CustomProceduralTexture;
  54642. }(BABYLON.ProceduralTexture));
  54643. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  54644. })(BABYLON || (BABYLON = {}));
  54645. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  54646. var BABYLON;
  54647. (function (BABYLON) {
  54648. var FreeCameraGamepadInput = /** @class */ (function () {
  54649. function FreeCameraGamepadInput() {
  54650. this.gamepadAngularSensibility = 200;
  54651. this.gamepadMoveSensibility = 40;
  54652. // private members
  54653. this._cameraTransform = BABYLON.Matrix.Identity();
  54654. this._deltaTransform = BABYLON.Vector3.Zero();
  54655. this._vector3 = BABYLON.Vector3.Zero();
  54656. this._vector2 = BABYLON.Vector2.Zero();
  54657. }
  54658. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54659. var _this = this;
  54660. var manager = this.camera.getScene().gamepadManager;
  54661. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54662. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54663. // prioritize XBOX gamepads.
  54664. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54665. _this.gamepad = gamepad;
  54666. }
  54667. }
  54668. });
  54669. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54670. if (_this.gamepad === gamepad) {
  54671. _this.gamepad = null;
  54672. }
  54673. });
  54674. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54675. };
  54676. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  54677. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54678. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54679. this.gamepad = null;
  54680. };
  54681. FreeCameraGamepadInput.prototype.checkInputs = function () {
  54682. if (this.gamepad && this.gamepad.leftStick) {
  54683. var camera = this.camera;
  54684. var LSValues = this.gamepad.leftStick;
  54685. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  54686. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54687. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  54688. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  54689. var RSValues = this.gamepad.rightStick;
  54690. if (RSValues) {
  54691. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  54692. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  54693. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  54694. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  54695. }
  54696. else {
  54697. RSValues = { x: 0, y: 0 };
  54698. }
  54699. if (!camera.rotationQuaternion) {
  54700. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  54701. }
  54702. else {
  54703. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  54704. }
  54705. var speed = camera._computeLocalCameraSpeed() * 50.0;
  54706. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  54707. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  54708. camera.cameraDirection.addInPlace(this._deltaTransform);
  54709. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  54710. camera.cameraRotation.addInPlace(this._vector2);
  54711. }
  54712. };
  54713. FreeCameraGamepadInput.prototype.getClassName = function () {
  54714. return "FreeCameraGamepadInput";
  54715. };
  54716. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  54717. return "gamepad";
  54718. };
  54719. __decorate([
  54720. BABYLON.serialize()
  54721. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  54722. __decorate([
  54723. BABYLON.serialize()
  54724. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54725. return FreeCameraGamepadInput;
  54726. }());
  54727. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  54728. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  54729. })(BABYLON || (BABYLON = {}));
  54730. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  54731. var BABYLON;
  54732. (function (BABYLON) {
  54733. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  54734. function ArcRotateCameraGamepadInput() {
  54735. this.gamepadRotationSensibility = 80;
  54736. this.gamepadMoveSensibility = 40;
  54737. }
  54738. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54739. var _this = this;
  54740. var manager = this.camera.getScene().gamepadManager;
  54741. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54742. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54743. // prioritize XBOX gamepads.
  54744. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54745. _this.gamepad = gamepad;
  54746. }
  54747. }
  54748. });
  54749. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54750. if (_this.gamepad === gamepad) {
  54751. _this.gamepad = null;
  54752. }
  54753. });
  54754. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54755. };
  54756. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  54757. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54758. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54759. this.gamepad = null;
  54760. };
  54761. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  54762. if (this.gamepad) {
  54763. var camera = this.camera;
  54764. var RSValues = this.gamepad.rightStick;
  54765. if (RSValues) {
  54766. if (RSValues.x != 0) {
  54767. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  54768. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  54769. camera.inertialAlphaOffset += normalizedRX;
  54770. }
  54771. }
  54772. if (RSValues.y != 0) {
  54773. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  54774. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  54775. camera.inertialBetaOffset += normalizedRY;
  54776. }
  54777. }
  54778. }
  54779. var LSValues = this.gamepad.leftStick;
  54780. if (LSValues && LSValues.y != 0) {
  54781. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54782. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  54783. this.camera.inertialRadiusOffset -= normalizedLY;
  54784. }
  54785. }
  54786. }
  54787. };
  54788. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  54789. return "ArcRotateCameraGamepadInput";
  54790. };
  54791. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  54792. return "gamepad";
  54793. };
  54794. __decorate([
  54795. BABYLON.serialize()
  54796. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  54797. __decorate([
  54798. BABYLON.serialize()
  54799. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54800. return ArcRotateCameraGamepadInput;
  54801. }());
  54802. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  54803. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  54804. })(BABYLON || (BABYLON = {}));
  54805. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  54806. var BABYLON;
  54807. (function (BABYLON) {
  54808. var GamepadManager = /** @class */ (function () {
  54809. function GamepadManager() {
  54810. var _this = this;
  54811. this._babylonGamepads = [];
  54812. this._oneGamepadConnected = false;
  54813. this._isMonitoring = false;
  54814. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  54815. if (!BABYLON.Tools.IsWindowObjectExist()) {
  54816. this._gamepadEventSupported = false;
  54817. }
  54818. else {
  54819. this._gamepadEventSupported = 'GamepadEvent' in window;
  54820. this._gamepadSupport = (navigator.getGamepads ||
  54821. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  54822. }
  54823. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  54824. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  54825. for (var i in _this._babylonGamepads) {
  54826. var gamepad = _this._babylonGamepads[i];
  54827. if (gamepad && gamepad._isConnected) {
  54828. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  54829. }
  54830. }
  54831. });
  54832. this._onGamepadConnectedEvent = function (evt) {
  54833. var gamepad = evt.gamepad;
  54834. if (gamepad.index in _this._babylonGamepads) {
  54835. if (_this._babylonGamepads[gamepad.index].isConnected) {
  54836. return;
  54837. }
  54838. }
  54839. var newGamepad;
  54840. if (_this._babylonGamepads[gamepad.index]) {
  54841. newGamepad = _this._babylonGamepads[gamepad.index];
  54842. newGamepad.browserGamepad = gamepad;
  54843. newGamepad._isConnected = true;
  54844. }
  54845. else {
  54846. newGamepad = _this._addNewGamepad(gamepad);
  54847. }
  54848. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54849. _this._startMonitoringGamepads();
  54850. };
  54851. this._onGamepadDisconnectedEvent = function (evt) {
  54852. var gamepad = evt.gamepad;
  54853. // Remove the gamepad from the list of gamepads to monitor.
  54854. for (var i in _this._babylonGamepads) {
  54855. if (_this._babylonGamepads[i].index === gamepad.index) {
  54856. var disconnectedGamepad = _this._babylonGamepads[i];
  54857. disconnectedGamepad._isConnected = false;
  54858. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  54859. break;
  54860. }
  54861. }
  54862. };
  54863. if (this._gamepadSupport) {
  54864. //first add already-connected gamepads
  54865. this._updateGamepadObjects();
  54866. if (this._babylonGamepads.length) {
  54867. this._startMonitoringGamepads();
  54868. }
  54869. // Checking if the gamepad connected event is supported (like in Firefox)
  54870. if (this._gamepadEventSupported) {
  54871. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54872. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  54873. }
  54874. else {
  54875. this._startMonitoringGamepads();
  54876. }
  54877. }
  54878. }
  54879. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  54880. get: function () {
  54881. return this._babylonGamepads;
  54882. },
  54883. enumerable: true,
  54884. configurable: true
  54885. });
  54886. GamepadManager.prototype.getGamepadByType = function (type) {
  54887. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  54888. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  54889. var gamepad = _a[_i];
  54890. if (gamepad && gamepad.type === type) {
  54891. return gamepad;
  54892. }
  54893. }
  54894. return null;
  54895. };
  54896. GamepadManager.prototype.dispose = function () {
  54897. if (this._gamepadEventSupported) {
  54898. if (this._onGamepadConnectedEvent) {
  54899. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  54900. }
  54901. if (this._onGamepadDisconnectedEvent) {
  54902. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  54903. }
  54904. this._onGamepadConnectedEvent = null;
  54905. this._onGamepadDisconnectedEvent = null;
  54906. }
  54907. this._babylonGamepads.forEach(function (gamepad) {
  54908. gamepad.dispose();
  54909. });
  54910. this.onGamepadConnectedObservable.clear();
  54911. this.onGamepadDisconnectedObservable.clear();
  54912. this._oneGamepadConnected = false;
  54913. this._stopMonitoringGamepads();
  54914. this._babylonGamepads = [];
  54915. };
  54916. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  54917. if (!this._oneGamepadConnected) {
  54918. this._oneGamepadConnected = true;
  54919. }
  54920. var newGamepad;
  54921. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  54922. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54923. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  54924. }
  54925. else if (gamepad.pose) {
  54926. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  54927. }
  54928. else {
  54929. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  54930. }
  54931. this._babylonGamepads[newGamepad.index] = newGamepad;
  54932. return newGamepad;
  54933. };
  54934. GamepadManager.prototype._startMonitoringGamepads = function () {
  54935. if (!this._isMonitoring) {
  54936. this._isMonitoring = true;
  54937. this._checkGamepadsStatus();
  54938. }
  54939. };
  54940. GamepadManager.prototype._stopMonitoringGamepads = function () {
  54941. this._isMonitoring = false;
  54942. };
  54943. GamepadManager.prototype._checkGamepadsStatus = function () {
  54944. var _this = this;
  54945. // Hack to be compatible Chrome
  54946. this._updateGamepadObjects();
  54947. for (var i in this._babylonGamepads) {
  54948. var gamepad = this._babylonGamepads[i];
  54949. if (!gamepad || !gamepad.isConnected) {
  54950. continue;
  54951. }
  54952. gamepad.update();
  54953. }
  54954. if (this._isMonitoring) {
  54955. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  54956. }
  54957. };
  54958. // This function is called only on Chrome, which does not properly support
  54959. // connection/disconnection events and forces you to recopy again the gamepad object
  54960. GamepadManager.prototype._updateGamepadObjects = function () {
  54961. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54962. for (var i = 0; i < gamepads.length; i++) {
  54963. if (gamepads[i]) {
  54964. if (!this._babylonGamepads[gamepads[i].index]) {
  54965. var newGamepad = this._addNewGamepad(gamepads[i]);
  54966. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54967. }
  54968. else {
  54969. // Forced to copy again this object for Chrome for unknown reason
  54970. this._babylonGamepads[i].browserGamepad = gamepads[i];
  54971. if (!this._babylonGamepads[i].isConnected) {
  54972. this._babylonGamepads[i]._isConnected = true;
  54973. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  54974. }
  54975. }
  54976. }
  54977. }
  54978. };
  54979. return GamepadManager;
  54980. }());
  54981. BABYLON.GamepadManager = GamepadManager;
  54982. })(BABYLON || (BABYLON = {}));
  54983. //# sourceMappingURL=babylon.gamepadManager.js.map
  54984. var BABYLON;
  54985. (function (BABYLON) {
  54986. var StickValues = /** @class */ (function () {
  54987. function StickValues(x, y) {
  54988. this.x = x;
  54989. this.y = y;
  54990. }
  54991. return StickValues;
  54992. }());
  54993. BABYLON.StickValues = StickValues;
  54994. var Gamepad = /** @class */ (function () {
  54995. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  54996. if (leftStickX === void 0) { leftStickX = 0; }
  54997. if (leftStickY === void 0) { leftStickY = 1; }
  54998. if (rightStickX === void 0) { rightStickX = 2; }
  54999. if (rightStickY === void 0) { rightStickY = 3; }
  55000. this.id = id;
  55001. this.index = index;
  55002. this.browserGamepad = browserGamepad;
  55003. this._isConnected = true;
  55004. this.type = Gamepad.GAMEPAD;
  55005. this._leftStickAxisX = leftStickX;
  55006. this._leftStickAxisY = leftStickY;
  55007. this._rightStickAxisX = rightStickX;
  55008. this._rightStickAxisY = rightStickY;
  55009. if (this.browserGamepad.axes.length >= 2) {
  55010. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55011. }
  55012. if (this.browserGamepad.axes.length >= 4) {
  55013. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55014. }
  55015. }
  55016. Object.defineProperty(Gamepad.prototype, "isConnected", {
  55017. get: function () {
  55018. return this._isConnected;
  55019. },
  55020. enumerable: true,
  55021. configurable: true
  55022. });
  55023. Gamepad.prototype.onleftstickchanged = function (callback) {
  55024. this._onleftstickchanged = callback;
  55025. };
  55026. Gamepad.prototype.onrightstickchanged = function (callback) {
  55027. this._onrightstickchanged = callback;
  55028. };
  55029. Object.defineProperty(Gamepad.prototype, "leftStick", {
  55030. get: function () {
  55031. return this._leftStick;
  55032. },
  55033. set: function (newValues) {
  55034. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  55035. this._onleftstickchanged(newValues);
  55036. }
  55037. this._leftStick = newValues;
  55038. },
  55039. enumerable: true,
  55040. configurable: true
  55041. });
  55042. Object.defineProperty(Gamepad.prototype, "rightStick", {
  55043. get: function () {
  55044. return this._rightStick;
  55045. },
  55046. set: function (newValues) {
  55047. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  55048. this._onrightstickchanged(newValues);
  55049. }
  55050. this._rightStick = newValues;
  55051. },
  55052. enumerable: true,
  55053. configurable: true
  55054. });
  55055. Gamepad.prototype.update = function () {
  55056. if (this._leftStick) {
  55057. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55058. }
  55059. if (this._rightStick) {
  55060. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55061. }
  55062. };
  55063. Gamepad.prototype.dispose = function () {
  55064. };
  55065. Gamepad.GAMEPAD = 0;
  55066. Gamepad.GENERIC = 1;
  55067. Gamepad.XBOX = 2;
  55068. Gamepad.POSE_ENABLED = 3;
  55069. return Gamepad;
  55070. }());
  55071. BABYLON.Gamepad = Gamepad;
  55072. var GenericPad = /** @class */ (function (_super) {
  55073. __extends(GenericPad, _super);
  55074. function GenericPad(id, index, browserGamepad) {
  55075. var _this = _super.call(this, id, index, browserGamepad) || this;
  55076. _this.onButtonDownObservable = new BABYLON.Observable();
  55077. _this.onButtonUpObservable = new BABYLON.Observable();
  55078. _this.type = Gamepad.GENERIC;
  55079. _this._buttons = new Array(browserGamepad.buttons.length);
  55080. return _this;
  55081. }
  55082. GenericPad.prototype.onbuttondown = function (callback) {
  55083. this._onbuttondown = callback;
  55084. };
  55085. GenericPad.prototype.onbuttonup = function (callback) {
  55086. this._onbuttonup = callback;
  55087. };
  55088. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55089. if (newValue !== currentValue) {
  55090. if (newValue === 1) {
  55091. if (this._onbuttondown) {
  55092. this._onbuttondown(buttonIndex);
  55093. }
  55094. this.onButtonDownObservable.notifyObservers(buttonIndex);
  55095. }
  55096. if (newValue === 0) {
  55097. if (this._onbuttonup) {
  55098. this._onbuttonup(buttonIndex);
  55099. }
  55100. this.onButtonUpObservable.notifyObservers(buttonIndex);
  55101. }
  55102. }
  55103. return newValue;
  55104. };
  55105. GenericPad.prototype.update = function () {
  55106. _super.prototype.update.call(this);
  55107. for (var index = 0; index < this._buttons.length; index++) {
  55108. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  55109. }
  55110. };
  55111. return GenericPad;
  55112. }(Gamepad));
  55113. BABYLON.GenericPad = GenericPad;
  55114. })(BABYLON || (BABYLON = {}));
  55115. //# sourceMappingURL=babylon.gamepad.js.map
  55116. var BABYLON;
  55117. (function (BABYLON) {
  55118. var Xbox360Button;
  55119. (function (Xbox360Button) {
  55120. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55121. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55122. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55123. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55124. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55125. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55126. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55127. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55128. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55129. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55130. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55131. var Xbox360Dpad;
  55132. (function (Xbox360Dpad) {
  55133. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55134. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55135. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55136. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55137. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55138. var Xbox360Pad = /** @class */ (function (_super) {
  55139. __extends(Xbox360Pad, _super);
  55140. function Xbox360Pad(id, index, gamepad, xboxOne) {
  55141. if (xboxOne === void 0) { xboxOne = false; }
  55142. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  55143. _this._leftTrigger = 0;
  55144. _this._rightTrigger = 0;
  55145. _this.onButtonDownObservable = new BABYLON.Observable();
  55146. _this.onButtonUpObservable = new BABYLON.Observable();
  55147. _this.onPadDownObservable = new BABYLON.Observable();
  55148. _this.onPadUpObservable = new BABYLON.Observable();
  55149. _this._buttonA = 0;
  55150. _this._buttonB = 0;
  55151. _this._buttonX = 0;
  55152. _this._buttonY = 0;
  55153. _this._buttonBack = 0;
  55154. _this._buttonStart = 0;
  55155. _this._buttonLB = 0;
  55156. _this._buttonRB = 0;
  55157. _this._buttonLeftStick = 0;
  55158. _this._buttonRightStick = 0;
  55159. _this._dPadUp = 0;
  55160. _this._dPadDown = 0;
  55161. _this._dPadLeft = 0;
  55162. _this._dPadRight = 0;
  55163. _this._isXboxOnePad = false;
  55164. _this.type = BABYLON.Gamepad.XBOX;
  55165. _this._isXboxOnePad = xboxOne;
  55166. return _this;
  55167. }
  55168. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55169. this._onlefttriggerchanged = callback;
  55170. };
  55171. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55172. this._onrighttriggerchanged = callback;
  55173. };
  55174. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55175. get: function () {
  55176. return this._leftTrigger;
  55177. },
  55178. set: function (newValue) {
  55179. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55180. this._onlefttriggerchanged(newValue);
  55181. }
  55182. this._leftTrigger = newValue;
  55183. },
  55184. enumerable: true,
  55185. configurable: true
  55186. });
  55187. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55188. get: function () {
  55189. return this._rightTrigger;
  55190. },
  55191. set: function (newValue) {
  55192. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55193. this._onrighttriggerchanged(newValue);
  55194. }
  55195. this._rightTrigger = newValue;
  55196. },
  55197. enumerable: true,
  55198. configurable: true
  55199. });
  55200. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55201. this._onbuttondown = callback;
  55202. };
  55203. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55204. this._onbuttonup = callback;
  55205. };
  55206. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55207. this._ondpaddown = callback;
  55208. };
  55209. Xbox360Pad.prototype.ondpadup = function (callback) {
  55210. this._ondpadup = callback;
  55211. };
  55212. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55213. if (newValue !== currentValue) {
  55214. if (newValue === 1) {
  55215. if (this._onbuttondown) {
  55216. this._onbuttondown(buttonType);
  55217. }
  55218. this.onButtonDownObservable.notifyObservers(buttonType);
  55219. }
  55220. if (newValue === 0) {
  55221. if (this._onbuttonup) {
  55222. this._onbuttonup(buttonType);
  55223. }
  55224. this.onButtonUpObservable.notifyObservers(buttonType);
  55225. }
  55226. }
  55227. return newValue;
  55228. };
  55229. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55230. if (newValue !== currentValue) {
  55231. if (newValue === 1) {
  55232. if (this._ondpaddown) {
  55233. this._ondpaddown(buttonType);
  55234. }
  55235. this.onPadDownObservable.notifyObservers(buttonType);
  55236. }
  55237. if (newValue === 0) {
  55238. if (this._ondpadup) {
  55239. this._ondpadup(buttonType);
  55240. }
  55241. this.onPadUpObservable.notifyObservers(buttonType);
  55242. }
  55243. }
  55244. return newValue;
  55245. };
  55246. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55247. get: function () {
  55248. return this._buttonA;
  55249. },
  55250. set: function (value) {
  55251. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55252. },
  55253. enumerable: true,
  55254. configurable: true
  55255. });
  55256. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55257. get: function () {
  55258. return this._buttonB;
  55259. },
  55260. set: function (value) {
  55261. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55262. },
  55263. enumerable: true,
  55264. configurable: true
  55265. });
  55266. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55267. get: function () {
  55268. return this._buttonX;
  55269. },
  55270. set: function (value) {
  55271. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55272. },
  55273. enumerable: true,
  55274. configurable: true
  55275. });
  55276. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55277. get: function () {
  55278. return this._buttonY;
  55279. },
  55280. set: function (value) {
  55281. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55282. },
  55283. enumerable: true,
  55284. configurable: true
  55285. });
  55286. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55287. get: function () {
  55288. return this._buttonStart;
  55289. },
  55290. set: function (value) {
  55291. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55292. },
  55293. enumerable: true,
  55294. configurable: true
  55295. });
  55296. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55297. get: function () {
  55298. return this._buttonBack;
  55299. },
  55300. set: function (value) {
  55301. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55302. },
  55303. enumerable: true,
  55304. configurable: true
  55305. });
  55306. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55307. get: function () {
  55308. return this._buttonLB;
  55309. },
  55310. set: function (value) {
  55311. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55312. },
  55313. enumerable: true,
  55314. configurable: true
  55315. });
  55316. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55317. get: function () {
  55318. return this._buttonRB;
  55319. },
  55320. set: function (value) {
  55321. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55322. },
  55323. enumerable: true,
  55324. configurable: true
  55325. });
  55326. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55327. get: function () {
  55328. return this._buttonLeftStick;
  55329. },
  55330. set: function (value) {
  55331. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55332. },
  55333. enumerable: true,
  55334. configurable: true
  55335. });
  55336. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55337. get: function () {
  55338. return this._buttonRightStick;
  55339. },
  55340. set: function (value) {
  55341. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55342. },
  55343. enumerable: true,
  55344. configurable: true
  55345. });
  55346. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55347. get: function () {
  55348. return this._dPadUp;
  55349. },
  55350. set: function (value) {
  55351. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55352. },
  55353. enumerable: true,
  55354. configurable: true
  55355. });
  55356. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55357. get: function () {
  55358. return this._dPadDown;
  55359. },
  55360. set: function (value) {
  55361. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55362. },
  55363. enumerable: true,
  55364. configurable: true
  55365. });
  55366. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55367. get: function () {
  55368. return this._dPadLeft;
  55369. },
  55370. set: function (value) {
  55371. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55372. },
  55373. enumerable: true,
  55374. configurable: true
  55375. });
  55376. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55377. get: function () {
  55378. return this._dPadRight;
  55379. },
  55380. set: function (value) {
  55381. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55382. },
  55383. enumerable: true,
  55384. configurable: true
  55385. });
  55386. Xbox360Pad.prototype.update = function () {
  55387. _super.prototype.update.call(this);
  55388. if (this._isXboxOnePad) {
  55389. this.buttonA = this.browserGamepad.buttons[0].value;
  55390. this.buttonB = this.browserGamepad.buttons[1].value;
  55391. this.buttonX = this.browserGamepad.buttons[2].value;
  55392. this.buttonY = this.browserGamepad.buttons[3].value;
  55393. this.buttonLB = this.browserGamepad.buttons[4].value;
  55394. this.buttonRB = this.browserGamepad.buttons[5].value;
  55395. this.leftTrigger = this.browserGamepad.axes[2];
  55396. this.rightTrigger = this.browserGamepad.axes[5];
  55397. this.buttonBack = this.browserGamepad.buttons[9].value;
  55398. this.buttonStart = this.browserGamepad.buttons[8].value;
  55399. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  55400. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  55401. this.dPadUp = this.browserGamepad.buttons[11].value;
  55402. this.dPadDown = this.browserGamepad.buttons[12].value;
  55403. this.dPadLeft = this.browserGamepad.buttons[13].value;
  55404. this.dPadRight = this.browserGamepad.buttons[14].value;
  55405. }
  55406. else {
  55407. this.buttonA = this.browserGamepad.buttons[0].value;
  55408. this.buttonB = this.browserGamepad.buttons[1].value;
  55409. this.buttonX = this.browserGamepad.buttons[2].value;
  55410. this.buttonY = this.browserGamepad.buttons[3].value;
  55411. this.buttonLB = this.browserGamepad.buttons[4].value;
  55412. this.buttonRB = this.browserGamepad.buttons[5].value;
  55413. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55414. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55415. this.buttonBack = this.browserGamepad.buttons[8].value;
  55416. this.buttonStart = this.browserGamepad.buttons[9].value;
  55417. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55418. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55419. this.dPadUp = this.browserGamepad.buttons[12].value;
  55420. this.dPadDown = this.browserGamepad.buttons[13].value;
  55421. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55422. this.dPadRight = this.browserGamepad.buttons[15].value;
  55423. }
  55424. };
  55425. return Xbox360Pad;
  55426. }(BABYLON.Gamepad));
  55427. BABYLON.Xbox360Pad = Xbox360Pad;
  55428. })(BABYLON || (BABYLON = {}));
  55429. //# sourceMappingURL=babylon.xboxGamepad.js.map
  55430. var BABYLON;
  55431. (function (BABYLON) {
  55432. var PoseEnabledControllerType;
  55433. (function (PoseEnabledControllerType) {
  55434. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  55435. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  55436. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  55437. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  55438. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  55439. var PoseEnabledControllerHelper = /** @class */ (function () {
  55440. function PoseEnabledControllerHelper() {
  55441. }
  55442. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  55443. // Oculus Touch
  55444. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  55445. return new BABYLON.OculusTouchController(vrGamepad);
  55446. }
  55447. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  55448. return new BABYLON.WindowsMotionController(vrGamepad);
  55449. }
  55450. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  55451. return new BABYLON.ViveController(vrGamepad);
  55452. }
  55453. else {
  55454. return new BABYLON.GenericController(vrGamepad);
  55455. }
  55456. };
  55457. return PoseEnabledControllerHelper;
  55458. }());
  55459. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  55460. var PoseEnabledController = /** @class */ (function (_super) {
  55461. __extends(PoseEnabledController, _super);
  55462. function PoseEnabledController(browserGamepad) {
  55463. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  55464. _this.deviceScaleFactor = 1;
  55465. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  55466. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  55467. _this.controllerType = PoseEnabledControllerType.GENERIC;
  55468. _this.position = BABYLON.Vector3.Zero();
  55469. _this.rotationQuaternion = new BABYLON.Quaternion();
  55470. _this.devicePosition = BABYLON.Vector3.Zero();
  55471. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  55472. _this._calculatedPosition = BABYLON.Vector3.Zero();
  55473. _this._calculatedRotation = new BABYLON.Quaternion();
  55474. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  55475. return _this;
  55476. }
  55477. PoseEnabledController.prototype.update = function () {
  55478. _super.prototype.update.call(this);
  55479. var pose = this.browserGamepad.pose;
  55480. this.updateFromDevice(pose);
  55481. if (this._mesh) {
  55482. this._mesh.position.copyFrom(this._calculatedPosition);
  55483. if (this._mesh.rotationQuaternion) {
  55484. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  55485. }
  55486. }
  55487. };
  55488. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  55489. if (poseData) {
  55490. this.rawPose = poseData;
  55491. if (poseData.position) {
  55492. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  55493. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  55494. this.devicePosition.z *= -1;
  55495. }
  55496. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  55497. this._calculatedPosition.addInPlace(this.position);
  55498. }
  55499. var pose = this.rawPose;
  55500. if (poseData.orientation && pose.orientation) {
  55501. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  55502. if (this._mesh) {
  55503. if (this._mesh.getScene().useRightHandedSystem) {
  55504. this.deviceRotationQuaternion.z *= -1;
  55505. this.deviceRotationQuaternion.w *= -1;
  55506. }
  55507. else {
  55508. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  55509. }
  55510. }
  55511. // if the camera is set, rotate to the camera's rotation
  55512. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  55513. }
  55514. }
  55515. };
  55516. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  55517. if (this._mesh) {
  55518. this._mesh.parent = null;
  55519. }
  55520. this._mesh = mesh;
  55521. if (this._poseControlledCamera) {
  55522. this._mesh.parent = this._poseControlledCamera;
  55523. }
  55524. if (!this._mesh.rotationQuaternion) {
  55525. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  55526. }
  55527. };
  55528. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  55529. this._poseControlledCamera = camera;
  55530. if (this._mesh) {
  55531. this._mesh.parent = this._poseControlledCamera;
  55532. }
  55533. };
  55534. PoseEnabledController.prototype.dispose = function () {
  55535. if (this._mesh) {
  55536. this._mesh.dispose();
  55537. }
  55538. this._mesh = null;
  55539. _super.prototype.dispose.call(this);
  55540. };
  55541. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  55542. get: function () {
  55543. return this._mesh;
  55544. },
  55545. enumerable: true,
  55546. configurable: true
  55547. });
  55548. PoseEnabledController.prototype.getForwardRay = function (length) {
  55549. if (length === void 0) { length = 100; }
  55550. if (!this.mesh) {
  55551. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  55552. }
  55553. var m = this.mesh.getWorldMatrix();
  55554. var origin = m.getTranslation();
  55555. var forward = new BABYLON.Vector3(0, 0, -1);
  55556. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55557. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55558. return new BABYLON.Ray(origin, direction, length);
  55559. };
  55560. return PoseEnabledController;
  55561. }(BABYLON.Gamepad));
  55562. BABYLON.PoseEnabledController = PoseEnabledController;
  55563. })(BABYLON || (BABYLON = {}));
  55564. //# sourceMappingURL=babylon.poseEnabledController.js.map
  55565. var BABYLON;
  55566. (function (BABYLON) {
  55567. var WebVRController = /** @class */ (function (_super) {
  55568. __extends(WebVRController, _super);
  55569. function WebVRController(vrGamepad) {
  55570. var _this = _super.call(this, vrGamepad) || this;
  55571. // Observables
  55572. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  55573. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  55574. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  55575. _this.onPadStateChangedObservable = new BABYLON.Observable();
  55576. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  55577. _this.pad = { x: 0, y: 0 };
  55578. // avoid GC, store state in a tmp object
  55579. _this._changes = {
  55580. pressChanged: false,
  55581. touchChanged: false,
  55582. valueChanged: false,
  55583. changed: false
  55584. };
  55585. _this._buttons = new Array(vrGamepad.buttons.length);
  55586. _this.hand = vrGamepad.hand;
  55587. return _this;
  55588. }
  55589. WebVRController.prototype.onButtonStateChange = function (callback) {
  55590. this._onButtonStateChange = callback;
  55591. };
  55592. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  55593. get: function () {
  55594. return this._defaultModel;
  55595. },
  55596. enumerable: true,
  55597. configurable: true
  55598. });
  55599. WebVRController.prototype.update = function () {
  55600. _super.prototype.update.call(this);
  55601. for (var index = 0; index < this._buttons.length; index++) {
  55602. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  55603. }
  55604. ;
  55605. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  55606. this.pad.x = this.leftStick.x;
  55607. this.pad.y = this.leftStick.y;
  55608. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  55609. }
  55610. };
  55611. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  55612. if (!newState) {
  55613. newState = {
  55614. pressed: false,
  55615. touched: false,
  55616. value: 0
  55617. };
  55618. }
  55619. if (!currentState) {
  55620. this._buttons[buttonIndex] = {
  55621. pressed: newState.pressed,
  55622. touched: newState.touched,
  55623. value: newState.value
  55624. };
  55625. return;
  55626. }
  55627. this._checkChanges(newState, currentState);
  55628. if (this._changes.changed) {
  55629. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  55630. this.handleButtonChange(buttonIndex, newState, this._changes);
  55631. }
  55632. this._buttons[buttonIndex].pressed = newState.pressed;
  55633. this._buttons[buttonIndex].touched = newState.touched;
  55634. // oculus triggers are never 0, thou not touched.
  55635. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  55636. };
  55637. WebVRController.prototype._checkChanges = function (newState, currentState) {
  55638. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  55639. this._changes.touchChanged = newState.touched !== currentState.touched;
  55640. this._changes.valueChanged = newState.value !== currentState.value;
  55641. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  55642. return this._changes;
  55643. };
  55644. WebVRController.prototype.dispose = function () {
  55645. _super.prototype.dispose.call(this);
  55646. this.onTriggerStateChangedObservable.clear();
  55647. this.onMainButtonStateChangedObservable.clear();
  55648. this.onSecondaryButtonStateChangedObservable.clear();
  55649. this.onPadStateChangedObservable.clear();
  55650. this.onPadValuesChangedObservable.clear();
  55651. };
  55652. return WebVRController;
  55653. }(BABYLON.PoseEnabledController));
  55654. BABYLON.WebVRController = WebVRController;
  55655. })(BABYLON || (BABYLON = {}));
  55656. //# sourceMappingURL=babylon.webVRController.js.map
  55657. var BABYLON;
  55658. (function (BABYLON) {
  55659. var OculusTouchController = /** @class */ (function (_super) {
  55660. __extends(OculusTouchController, _super);
  55661. function OculusTouchController(vrGamepad) {
  55662. var _this = _super.call(this, vrGamepad) || this;
  55663. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  55664. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  55665. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  55666. return _this;
  55667. }
  55668. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55669. var _this = this;
  55670. var meshName;
  55671. // Hand
  55672. if (this.hand === 'left') {
  55673. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  55674. }
  55675. else {
  55676. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  55677. }
  55678. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  55679. /*
  55680. Parent Mesh name: oculus_touch_left
  55681. - body
  55682. - trigger
  55683. - thumbstick
  55684. - grip
  55685. - button_y
  55686. - button_x
  55687. - button_enter
  55688. */
  55689. _this._defaultModel = newMeshes[1];
  55690. _this.attachToMesh(_this._defaultModel);
  55691. if (meshLoaded) {
  55692. meshLoaded(_this._defaultModel);
  55693. }
  55694. });
  55695. };
  55696. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  55697. // helper getters for left and right hand.
  55698. get: function () {
  55699. if (this.hand === 'right') {
  55700. return this.onMainButtonStateChangedObservable;
  55701. }
  55702. else {
  55703. throw new Error('No A button on left hand');
  55704. }
  55705. },
  55706. enumerable: true,
  55707. configurable: true
  55708. });
  55709. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  55710. get: function () {
  55711. if (this.hand === 'right') {
  55712. return this.onSecondaryButtonStateChangedObservable;
  55713. }
  55714. else {
  55715. throw new Error('No B button on left hand');
  55716. }
  55717. },
  55718. enumerable: true,
  55719. configurable: true
  55720. });
  55721. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  55722. get: function () {
  55723. if (this.hand === 'left') {
  55724. return this.onMainButtonStateChangedObservable;
  55725. }
  55726. else {
  55727. throw new Error('No X button on right hand');
  55728. }
  55729. },
  55730. enumerable: true,
  55731. configurable: true
  55732. });
  55733. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  55734. get: function () {
  55735. if (this.hand === 'left') {
  55736. return this.onSecondaryButtonStateChangedObservable;
  55737. }
  55738. else {
  55739. throw new Error('No Y button on right hand');
  55740. }
  55741. },
  55742. enumerable: true,
  55743. configurable: true
  55744. });
  55745. /*
  55746. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  55747. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  55748. 2) secondary trigger (same)
  55749. 3) A (right) X (left), touch, pressed = value
  55750. 4) B / Y
  55751. 5) thumb rest
  55752. */
  55753. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55754. var notifyObject = state; //{ state: state, changes: changes };
  55755. var triggerDirection = this.hand === 'right' ? -1 : 1;
  55756. switch (buttonIdx) {
  55757. case 0:
  55758. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55759. return;
  55760. case 1:// index trigger
  55761. if (this._defaultModel) {
  55762. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  55763. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  55764. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  55765. }
  55766. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55767. return;
  55768. case 2:// secondary trigger
  55769. if (this._defaultModel) {
  55770. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  55771. }
  55772. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  55773. return;
  55774. case 3:
  55775. if (this._defaultModel) {
  55776. if (notifyObject.pressed) {
  55777. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  55778. }
  55779. else {
  55780. (this._defaultModel.getChildren()[1]).position.y = 0;
  55781. }
  55782. }
  55783. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55784. return;
  55785. case 4:
  55786. if (this._defaultModel) {
  55787. if (notifyObject.pressed) {
  55788. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55789. }
  55790. else {
  55791. (this._defaultModel.getChildren()[2]).position.y = 0;
  55792. }
  55793. }
  55794. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55795. return;
  55796. case 5:
  55797. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  55798. return;
  55799. }
  55800. };
  55801. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  55802. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  55803. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  55804. return OculusTouchController;
  55805. }(BABYLON.WebVRController));
  55806. BABYLON.OculusTouchController = OculusTouchController;
  55807. })(BABYLON || (BABYLON = {}));
  55808. //# sourceMappingURL=babylon.oculusTouchController.js.map
  55809. var BABYLON;
  55810. (function (BABYLON) {
  55811. var ViveController = /** @class */ (function (_super) {
  55812. __extends(ViveController, _super);
  55813. function ViveController(vrGamepad) {
  55814. var _this = _super.call(this, vrGamepad) || this;
  55815. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  55816. return _this;
  55817. }
  55818. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55819. var _this = this;
  55820. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  55821. /*
  55822. Parent Mesh name: ViveWand
  55823. - body
  55824. - r_gripper
  55825. - l_gripper
  55826. - menu_button
  55827. - system_button
  55828. - trackpad
  55829. - trigger
  55830. - LED
  55831. */
  55832. _this._defaultModel = newMeshes[1];
  55833. _this.attachToMesh(_this._defaultModel);
  55834. if (meshLoaded) {
  55835. meshLoaded(_this._defaultModel);
  55836. }
  55837. });
  55838. };
  55839. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  55840. get: function () {
  55841. return this.onMainButtonStateChangedObservable;
  55842. },
  55843. enumerable: true,
  55844. configurable: true
  55845. });
  55846. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  55847. get: function () {
  55848. return this.onMainButtonStateChangedObservable;
  55849. },
  55850. enumerable: true,
  55851. configurable: true
  55852. });
  55853. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  55854. get: function () {
  55855. return this.onSecondaryButtonStateChangedObservable;
  55856. },
  55857. enumerable: true,
  55858. configurable: true
  55859. });
  55860. /**
  55861. * Vive mapping:
  55862. * 0: touchpad
  55863. * 1: trigger
  55864. * 2: left AND right buttons
  55865. * 3: menu button
  55866. */
  55867. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55868. var notifyObject = state; //{ state: state, changes: changes };
  55869. switch (buttonIdx) {
  55870. case 0:
  55871. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55872. return;
  55873. case 1:// index trigger
  55874. if (this._defaultModel) {
  55875. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  55876. }
  55877. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55878. return;
  55879. case 2:// left AND right button
  55880. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55881. return;
  55882. case 3:
  55883. if (this._defaultModel) {
  55884. if (notifyObject.pressed) {
  55885. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55886. }
  55887. else {
  55888. (this._defaultModel.getChildren()[2]).position.y = 0;
  55889. }
  55890. }
  55891. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55892. return;
  55893. }
  55894. };
  55895. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  55896. ViveController.MODEL_FILENAME = 'wand.babylon';
  55897. return ViveController;
  55898. }(BABYLON.WebVRController));
  55899. BABYLON.ViveController = ViveController;
  55900. })(BABYLON || (BABYLON = {}));
  55901. //# sourceMappingURL=babylon.viveController.js.map
  55902. var BABYLON;
  55903. (function (BABYLON) {
  55904. var GenericController = /** @class */ (function (_super) {
  55905. __extends(GenericController, _super);
  55906. function GenericController(vrGamepad) {
  55907. return _super.call(this, vrGamepad) || this;
  55908. }
  55909. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55910. var _this = this;
  55911. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  55912. _this._defaultModel = newMeshes[1];
  55913. _this.attachToMesh(_this._defaultModel);
  55914. if (meshLoaded) {
  55915. meshLoaded(_this._defaultModel);
  55916. }
  55917. });
  55918. };
  55919. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55920. console.log("Button id: " + buttonIdx + "state: ");
  55921. console.dir(state);
  55922. };
  55923. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  55924. GenericController.MODEL_FILENAME = 'generic.babylon';
  55925. return GenericController;
  55926. }(BABYLON.WebVRController));
  55927. BABYLON.GenericController = GenericController;
  55928. })(BABYLON || (BABYLON = {}));
  55929. //# sourceMappingURL=babylon.genericController.js.map
  55930. var BABYLON;
  55931. (function (BABYLON) {
  55932. var LoadedMeshInfo = /** @class */ (function () {
  55933. function LoadedMeshInfo() {
  55934. this.buttonMeshes = {};
  55935. this.axisMeshes = {};
  55936. }
  55937. return LoadedMeshInfo;
  55938. }());
  55939. var WindowsMotionController = /** @class */ (function (_super) {
  55940. __extends(WindowsMotionController, _super);
  55941. function WindowsMotionController(vrGamepad) {
  55942. var _this = _super.call(this, vrGamepad) || this;
  55943. _this._mapping = {
  55944. // Semantic button names
  55945. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  55946. // A mapping of the button name to glTF model node name
  55947. // that should be transformed by button value.
  55948. buttonMeshNames: {
  55949. 'trigger': 'SELECT',
  55950. 'menu': 'MENU',
  55951. 'grip': 'GRASP',
  55952. 'thumbstick': 'THUMBSTICK_PRESS',
  55953. 'trackpad': 'TOUCHPAD_PRESS'
  55954. },
  55955. // This mapping is used to translate from the Motion Controller to Babylon semantics
  55956. buttonObservableNames: {
  55957. 'trigger': 'onTriggerStateChangedObservable',
  55958. 'menu': 'onSecondaryButtonStateChangedObservable',
  55959. 'grip': 'onMainButtonStateChangedObservable',
  55960. 'thumbstick': 'onPadStateChangedObservable',
  55961. 'trackpad': 'onTrackpadChangedObservable'
  55962. },
  55963. // A mapping of the axis name to glTF model node name
  55964. // that should be transformed by axis value.
  55965. // This array mirrors the browserGamepad.axes array, such that
  55966. // the mesh corresponding to axis 0 is in this array index 0.
  55967. axisMeshNames: [
  55968. 'THUMBSTICK_X',
  55969. 'THUMBSTICK_Y',
  55970. 'TOUCHPAD_TOUCH_X',
  55971. 'TOUCHPAD_TOUCH_Y'
  55972. ],
  55973. pointingPoseMeshName: 'POINTING_POSE'
  55974. };
  55975. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  55976. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  55977. _this._loadedMeshInfo = null;
  55978. return _this;
  55979. }
  55980. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  55981. get: function () {
  55982. return this.onTriggerStateChangedObservable;
  55983. },
  55984. enumerable: true,
  55985. configurable: true
  55986. });
  55987. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  55988. get: function () {
  55989. return this.onSecondaryButtonStateChangedObservable;
  55990. },
  55991. enumerable: true,
  55992. configurable: true
  55993. });
  55994. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  55995. get: function () {
  55996. return this.onMainButtonStateChangedObservable;
  55997. },
  55998. enumerable: true,
  55999. configurable: true
  56000. });
  56001. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  56002. get: function () {
  56003. return this.onPadStateChangedObservable;
  56004. },
  56005. enumerable: true,
  56006. configurable: true
  56007. });
  56008. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  56009. get: function () {
  56010. return this.onTrackpadChangedObservable;
  56011. },
  56012. enumerable: true,
  56013. configurable: true
  56014. });
  56015. /**
  56016. * Called once per frame by the engine.
  56017. */
  56018. WindowsMotionController.prototype.update = function () {
  56019. _super.prototype.update.call(this);
  56020. // Only need to animate axes if there is a loaded mesh
  56021. if (this._loadedMeshInfo) {
  56022. if (this.browserGamepad.axes) {
  56023. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  56024. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  56025. }
  56026. }
  56027. }
  56028. };
  56029. /**
  56030. * Called once for each button that changed state since the last frame
  56031. * @param buttonIdx Which button index changed
  56032. * @param state New state of the button
  56033. * @param changes Which properties on the state changed since last frame
  56034. */
  56035. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56036. var buttonName = this._mapping.buttons[buttonIdx];
  56037. if (!buttonName) {
  56038. return;
  56039. }
  56040. // Only emit events for buttons that we know how to map from index to name
  56041. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  56042. if (observable) {
  56043. observable.notifyObservers(state);
  56044. }
  56045. this.lerpButtonTransform(buttonName, state.value);
  56046. };
  56047. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  56048. // If there is no loaded mesh, there is nothing to transform.
  56049. if (!this._loadedMeshInfo) {
  56050. return;
  56051. }
  56052. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  56053. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56054. return;
  56055. }
  56056. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  56057. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  56058. };
  56059. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  56060. if (!this._loadedMeshInfo) {
  56061. return;
  56062. }
  56063. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  56064. if (!meshInfo) {
  56065. return;
  56066. }
  56067. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56068. return;
  56069. }
  56070. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  56071. var lerpValue = axisValue * 0.5 + 0.5;
  56072. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  56073. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  56074. };
  56075. /**
  56076. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  56077. * @param scene scene in which to add meshes
  56078. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  56079. */
  56080. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  56081. var _this = this;
  56082. if (forceDefault === void 0) { forceDefault = false; }
  56083. var path;
  56084. var filename;
  56085. // Checking if GLB loader is present
  56086. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  56087. // Determine the device specific folder based on the ID suffix
  56088. var device = 'default';
  56089. if (this.id && !forceDefault) {
  56090. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  56091. device = ((match && match[0]) || device);
  56092. }
  56093. // Hand
  56094. if (this.hand === 'left') {
  56095. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  56096. }
  56097. else {
  56098. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  56099. }
  56100. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  56101. }
  56102. else {
  56103. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  56104. path = BABYLON.GenericController.MODEL_BASE_URL;
  56105. filename = BABYLON.GenericController.MODEL_FILENAME;
  56106. }
  56107. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  56108. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  56109. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  56110. if (!_this._loadedMeshInfo) {
  56111. return;
  56112. }
  56113. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  56114. _this.attachToMesh(_this._defaultModel);
  56115. if (meshLoaded) {
  56116. meshLoaded(_this._defaultModel);
  56117. }
  56118. }, null, function (scene, message) {
  56119. BABYLON.Tools.Log(message);
  56120. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  56121. if (!forceDefault) {
  56122. _this.initControllerMesh(scene, meshLoaded, true);
  56123. }
  56124. });
  56125. };
  56126. /**
  56127. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  56128. * can be transformed by button presses and axes values, based on this._mapping.
  56129. *
  56130. * @param scene scene in which the meshes exist
  56131. * @param meshes list of meshes that make up the controller model to process
  56132. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  56133. */
  56134. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  56135. var loadedMeshInfo = null;
  56136. // Create a new mesh to contain the glTF hierarchy
  56137. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  56138. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  56139. var childMesh = null;
  56140. for (var i = 0; i < meshes.length; i++) {
  56141. var mesh = meshes[i];
  56142. if (!mesh.parent) {
  56143. // Exclude controller meshes from picking results
  56144. mesh.isPickable = false;
  56145. // Handle root node, attach to the new parentMesh
  56146. childMesh = mesh;
  56147. break;
  56148. }
  56149. }
  56150. if (childMesh) {
  56151. childMesh.setParent(parentMesh);
  56152. // Create our mesh info. Note that this method will always return non-null.
  56153. loadedMeshInfo = this.createMeshInfo(parentMesh);
  56154. }
  56155. else {
  56156. BABYLON.Tools.Warn('Could not find root node in model file.');
  56157. }
  56158. return loadedMeshInfo;
  56159. };
  56160. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  56161. var loadedMeshInfo = new LoadedMeshInfo();
  56162. var i;
  56163. loadedMeshInfo.rootNode = rootNode;
  56164. // Reset the caches
  56165. loadedMeshInfo.buttonMeshes = {};
  56166. loadedMeshInfo.axisMeshes = {};
  56167. // Button Meshes
  56168. for (i = 0; i < this._mapping.buttons.length; i++) {
  56169. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  56170. if (!buttonMeshName) {
  56171. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  56172. continue;
  56173. }
  56174. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  56175. if (!buttonMesh) {
  56176. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  56177. continue;
  56178. }
  56179. var buttonMeshInfo = {
  56180. index: i,
  56181. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  56182. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  56183. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  56184. };
  56185. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  56186. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  56187. }
  56188. else {
  56189. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  56190. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  56191. '(VALUE: ' + !!buttonMeshInfo.value +
  56192. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  56193. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  56194. ')');
  56195. }
  56196. }
  56197. // Axis Meshes
  56198. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  56199. var axisMeshName = this._mapping.axisMeshNames[i];
  56200. if (!axisMeshName) {
  56201. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  56202. continue;
  56203. }
  56204. var axisMesh = getChildByName(rootNode, axisMeshName);
  56205. if (!axisMesh) {
  56206. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  56207. continue;
  56208. }
  56209. var axisMeshInfo = {
  56210. index: i,
  56211. value: getImmediateChildByName(axisMesh, 'VALUE'),
  56212. min: getImmediateChildByName(axisMesh, 'MIN'),
  56213. max: getImmediateChildByName(axisMesh, 'MAX')
  56214. };
  56215. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  56216. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  56217. }
  56218. else {
  56219. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  56220. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  56221. '(VALUE: ' + !!axisMeshInfo.value +
  56222. ', MIN: ' + !!axisMeshInfo.min +
  56223. ', MAX:' + !!axisMeshInfo.max +
  56224. ')');
  56225. }
  56226. }
  56227. // Pointing Ray
  56228. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  56229. if (!loadedMeshInfo.pointingPoseNode) {
  56230. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  56231. }
  56232. return loadedMeshInfo;
  56233. // Look through all children recursively. This will return null if no mesh exists with the given name.
  56234. function getChildByName(node, name) {
  56235. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  56236. }
  56237. // Look through only immediate children. This will return null if no mesh exists with the given name.
  56238. function getImmediateChildByName(node, name) {
  56239. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  56240. }
  56241. };
  56242. WindowsMotionController.prototype.getForwardRay = function (length) {
  56243. if (length === void 0) { length = 100; }
  56244. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  56245. return _super.prototype.getForwardRay.call(this, length);
  56246. }
  56247. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  56248. var origin = m.getTranslation();
  56249. var forward = new BABYLON.Vector3(0, 0, -1);
  56250. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56251. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56252. return new BABYLON.Ray(origin, direction, length);
  56253. };
  56254. WindowsMotionController.prototype.dispose = function () {
  56255. _super.prototype.dispose.call(this);
  56256. this.onTrackpadChangedObservable.clear();
  56257. };
  56258. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  56259. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  56260. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  56261. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  56262. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  56263. return WindowsMotionController;
  56264. }(BABYLON.WebVRController));
  56265. BABYLON.WindowsMotionController = WindowsMotionController;
  56266. })(BABYLON || (BABYLON = {}));
  56267. //# sourceMappingURL=babylon.windowsMotionController.js.map
  56268. var BABYLON;
  56269. (function (BABYLON) {
  56270. var FollowCamera = /** @class */ (function (_super) {
  56271. __extends(FollowCamera, _super);
  56272. function FollowCamera(name, position, scene, lockedTarget) {
  56273. if (lockedTarget === void 0) { lockedTarget = null; }
  56274. var _this = _super.call(this, name, position, scene) || this;
  56275. _this.radius = 12;
  56276. _this.rotationOffset = 0;
  56277. _this.heightOffset = 4;
  56278. _this.cameraAcceleration = 0.05;
  56279. _this.maxCameraSpeed = 20;
  56280. _this.lockedTarget = lockedTarget;
  56281. return _this;
  56282. }
  56283. FollowCamera.prototype.getRadians = function (degrees) {
  56284. return degrees * Math.PI / 180;
  56285. };
  56286. FollowCamera.prototype.follow = function (cameraTarget) {
  56287. if (!cameraTarget)
  56288. return;
  56289. var yRotation;
  56290. if (cameraTarget.rotationQuaternion) {
  56291. var rotMatrix = new BABYLON.Matrix();
  56292. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  56293. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  56294. }
  56295. else {
  56296. yRotation = cameraTarget.rotation.y;
  56297. }
  56298. var radians = this.getRadians(this.rotationOffset) + yRotation;
  56299. var targetPosition = cameraTarget.getAbsolutePosition();
  56300. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  56301. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  56302. var dx = targetX - this.position.x;
  56303. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  56304. var dz = (targetZ) - this.position.z;
  56305. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  56306. var vy = dy * this.cameraAcceleration;
  56307. var vz = dz * this.cameraAcceleration * 2;
  56308. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  56309. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56310. }
  56311. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  56312. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56313. }
  56314. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  56315. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56316. }
  56317. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  56318. this.setTarget(targetPosition);
  56319. };
  56320. FollowCamera.prototype._checkInputs = function () {
  56321. _super.prototype._checkInputs.call(this);
  56322. if (this.lockedTarget) {
  56323. this.follow(this.lockedTarget);
  56324. }
  56325. };
  56326. FollowCamera.prototype.getClassName = function () {
  56327. return "FollowCamera";
  56328. };
  56329. __decorate([
  56330. BABYLON.serialize()
  56331. ], FollowCamera.prototype, "radius", void 0);
  56332. __decorate([
  56333. BABYLON.serialize()
  56334. ], FollowCamera.prototype, "rotationOffset", void 0);
  56335. __decorate([
  56336. BABYLON.serialize()
  56337. ], FollowCamera.prototype, "heightOffset", void 0);
  56338. __decorate([
  56339. BABYLON.serialize()
  56340. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  56341. __decorate([
  56342. BABYLON.serialize()
  56343. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  56344. __decorate([
  56345. BABYLON.serializeAsMeshReference("lockedTargetId")
  56346. ], FollowCamera.prototype, "lockedTarget", void 0);
  56347. return FollowCamera;
  56348. }(BABYLON.TargetCamera));
  56349. BABYLON.FollowCamera = FollowCamera;
  56350. var ArcFollowCamera = /** @class */ (function (_super) {
  56351. __extends(ArcFollowCamera, _super);
  56352. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  56353. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  56354. _this.alpha = alpha;
  56355. _this.beta = beta;
  56356. _this.radius = radius;
  56357. _this.target = target;
  56358. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  56359. _this.follow();
  56360. return _this;
  56361. }
  56362. ArcFollowCamera.prototype.follow = function () {
  56363. if (!this.target) {
  56364. return;
  56365. }
  56366. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  56367. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  56368. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  56369. var targetPosition = this.target.getAbsolutePosition();
  56370. this.position = targetPosition.add(this._cartesianCoordinates);
  56371. this.setTarget(targetPosition);
  56372. };
  56373. ArcFollowCamera.prototype._checkInputs = function () {
  56374. _super.prototype._checkInputs.call(this);
  56375. this.follow();
  56376. };
  56377. ArcFollowCamera.prototype.getClassName = function () {
  56378. return "ArcFollowCamera";
  56379. };
  56380. return ArcFollowCamera;
  56381. }(BABYLON.TargetCamera));
  56382. BABYLON.ArcFollowCamera = ArcFollowCamera;
  56383. })(BABYLON || (BABYLON = {}));
  56384. //# sourceMappingURL=babylon.followCamera.js.map
  56385. var BABYLON;
  56386. (function (BABYLON) {
  56387. // We're mainly based on the logic defined into the FreeCamera code
  56388. var UniversalCamera = /** @class */ (function (_super) {
  56389. __extends(UniversalCamera, _super);
  56390. //-- end properties for backward compatibility for inputs
  56391. function UniversalCamera(name, position, scene) {
  56392. var _this = _super.call(this, name, position, scene) || this;
  56393. _this.inputs.addGamepad();
  56394. return _this;
  56395. }
  56396. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  56397. //-- Begin properties for backward compatibility for inputs
  56398. get: function () {
  56399. var gamepad = this.inputs.attached["gamepad"];
  56400. if (gamepad)
  56401. return gamepad.gamepadAngularSensibility;
  56402. return 0;
  56403. },
  56404. set: function (value) {
  56405. var gamepad = this.inputs.attached["gamepad"];
  56406. if (gamepad)
  56407. gamepad.gamepadAngularSensibility = value;
  56408. },
  56409. enumerable: true,
  56410. configurable: true
  56411. });
  56412. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  56413. get: function () {
  56414. var gamepad = this.inputs.attached["gamepad"];
  56415. if (gamepad)
  56416. return gamepad.gamepadMoveSensibility;
  56417. return 0;
  56418. },
  56419. set: function (value) {
  56420. var gamepad = this.inputs.attached["gamepad"];
  56421. if (gamepad)
  56422. gamepad.gamepadMoveSensibility = value;
  56423. },
  56424. enumerable: true,
  56425. configurable: true
  56426. });
  56427. UniversalCamera.prototype.getClassName = function () {
  56428. return "UniversalCamera";
  56429. };
  56430. return UniversalCamera;
  56431. }(BABYLON.TouchCamera));
  56432. BABYLON.UniversalCamera = UniversalCamera;
  56433. })(BABYLON || (BABYLON = {}));
  56434. //# sourceMappingURL=babylon.universalCamera.js.map
  56435. var BABYLON;
  56436. (function (BABYLON) {
  56437. // We're mainly based on the logic defined into the FreeCamera code
  56438. var GamepadCamera = /** @class */ (function (_super) {
  56439. __extends(GamepadCamera, _super);
  56440. //-- end properties for backward compatibility for inputs
  56441. function GamepadCamera(name, position, scene) {
  56442. return _super.call(this, name, position, scene) || this;
  56443. }
  56444. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  56445. //-- Begin properties for backward compatibility for inputs
  56446. get: function () {
  56447. var gamepad = this.inputs.attached["gamepad"];
  56448. if (gamepad)
  56449. return gamepad.gamepadAngularSensibility;
  56450. return 0;
  56451. },
  56452. set: function (value) {
  56453. var gamepad = this.inputs.attached["gamepad"];
  56454. if (gamepad)
  56455. gamepad.gamepadAngularSensibility = value;
  56456. },
  56457. enumerable: true,
  56458. configurable: true
  56459. });
  56460. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  56461. get: function () {
  56462. var gamepad = this.inputs.attached["gamepad"];
  56463. if (gamepad)
  56464. return gamepad.gamepadMoveSensibility;
  56465. return 0;
  56466. },
  56467. set: function (value) {
  56468. var gamepad = this.inputs.attached["gamepad"];
  56469. if (gamepad)
  56470. gamepad.gamepadMoveSensibility = value;
  56471. },
  56472. enumerable: true,
  56473. configurable: true
  56474. });
  56475. GamepadCamera.prototype.getClassName = function () {
  56476. return "GamepadCamera";
  56477. };
  56478. return GamepadCamera;
  56479. }(BABYLON.UniversalCamera));
  56480. BABYLON.GamepadCamera = GamepadCamera;
  56481. })(BABYLON || (BABYLON = {}));
  56482. //# sourceMappingURL=babylon.gamepadCamera.js.map
  56483. var BABYLON;
  56484. (function (BABYLON) {
  56485. var PostProcessRenderPipelineManager = /** @class */ (function () {
  56486. function PostProcessRenderPipelineManager() {
  56487. this._renderPipelines = {};
  56488. }
  56489. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  56490. this._renderPipelines[renderPipeline._name] = renderPipeline;
  56491. };
  56492. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  56493. if (unique === void 0) { unique = false; }
  56494. var renderPipeline = this._renderPipelines[renderPipelineName];
  56495. if (!renderPipeline) {
  56496. return;
  56497. }
  56498. renderPipeline._attachCameras(cameras, unique);
  56499. };
  56500. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  56501. var renderPipeline = this._renderPipelines[renderPipelineName];
  56502. if (!renderPipeline) {
  56503. return;
  56504. }
  56505. renderPipeline._detachCameras(cameras);
  56506. };
  56507. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56508. var renderPipeline = this._renderPipelines[renderPipelineName];
  56509. if (!renderPipeline) {
  56510. return;
  56511. }
  56512. renderPipeline._enableEffect(renderEffectName, cameras);
  56513. };
  56514. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56515. var renderPipeline = this._renderPipelines[renderPipelineName];
  56516. if (!renderPipeline) {
  56517. return;
  56518. }
  56519. renderPipeline._disableEffect(renderEffectName, cameras);
  56520. };
  56521. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  56522. var renderPipeline = this._renderPipelines[renderPipelineName];
  56523. if (!renderPipeline) {
  56524. return;
  56525. }
  56526. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  56527. };
  56528. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  56529. var renderPipeline = this._renderPipelines[renderPipelineName];
  56530. if (!renderPipeline) {
  56531. return;
  56532. }
  56533. renderPipeline._disableDisplayOnlyPass(cameras);
  56534. };
  56535. PostProcessRenderPipelineManager.prototype.update = function () {
  56536. for (var renderPipelineName in this._renderPipelines) {
  56537. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56538. var pipeline = this._renderPipelines[renderPipelineName];
  56539. if (!pipeline.isSupported) {
  56540. pipeline.dispose();
  56541. delete this._renderPipelines[renderPipelineName];
  56542. }
  56543. else {
  56544. pipeline._update();
  56545. }
  56546. }
  56547. }
  56548. };
  56549. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  56550. for (var renderPipelineName in this._renderPipelines) {
  56551. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56552. var pipeline = this._renderPipelines[renderPipelineName];
  56553. pipeline._rebuild();
  56554. }
  56555. }
  56556. };
  56557. PostProcessRenderPipelineManager.prototype.dispose = function () {
  56558. for (var renderPipelineName in this._renderPipelines) {
  56559. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56560. var pipeline = this._renderPipelines[renderPipelineName];
  56561. pipeline.dispose();
  56562. }
  56563. }
  56564. };
  56565. return PostProcessRenderPipelineManager;
  56566. }());
  56567. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  56568. })(BABYLON || (BABYLON = {}));
  56569. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  56570. var BABYLON;
  56571. (function (BABYLON) {
  56572. var PostProcessRenderPass = /** @class */ (function () {
  56573. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  56574. this._refCount = 0;
  56575. this._name = name;
  56576. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  56577. this.setRenderList(renderList);
  56578. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  56579. this._renderTexture.onAfterRenderObservable.add(afterRender);
  56580. this._scene = scene;
  56581. this._renderList = renderList;
  56582. }
  56583. // private
  56584. PostProcessRenderPass.prototype._incRefCount = function () {
  56585. if (this._refCount === 0) {
  56586. this._scene.customRenderTargets.push(this._renderTexture);
  56587. }
  56588. return ++this._refCount;
  56589. };
  56590. PostProcessRenderPass.prototype._decRefCount = function () {
  56591. this._refCount--;
  56592. if (this._refCount <= 0) {
  56593. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  56594. }
  56595. return this._refCount;
  56596. };
  56597. PostProcessRenderPass.prototype._update = function () {
  56598. this.setRenderList(this._renderList);
  56599. };
  56600. // public
  56601. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  56602. this._renderTexture.renderList = renderList;
  56603. };
  56604. PostProcessRenderPass.prototype.getRenderTexture = function () {
  56605. return this._renderTexture;
  56606. };
  56607. return PostProcessRenderPass;
  56608. }());
  56609. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  56610. })(BABYLON || (BABYLON = {}));
  56611. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  56612. var BABYLON;
  56613. (function (BABYLON) {
  56614. var PostProcessRenderEffect = /** @class */ (function () {
  56615. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  56616. this._engine = engine;
  56617. this._name = name;
  56618. this._singleInstance = singleInstance || true;
  56619. this._getPostProcess = getPostProcess;
  56620. this._cameras = {};
  56621. this._indicesForCamera = {};
  56622. this._postProcesses = {};
  56623. this._renderPasses = {};
  56624. this._renderEffectAsPasses = {};
  56625. }
  56626. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  56627. get: function () {
  56628. for (var index in this._postProcesses) {
  56629. if (!this._postProcesses[index].isSupported) {
  56630. return false;
  56631. }
  56632. }
  56633. return true;
  56634. },
  56635. enumerable: true,
  56636. configurable: true
  56637. });
  56638. PostProcessRenderEffect.prototype._update = function () {
  56639. for (var renderPassName in this._renderPasses) {
  56640. this._renderPasses[renderPassName]._update();
  56641. }
  56642. };
  56643. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  56644. this._renderPasses[renderPass._name] = renderPass;
  56645. this._linkParameters();
  56646. };
  56647. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  56648. delete this._renderPasses[renderPass._name];
  56649. this._linkParameters();
  56650. };
  56651. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  56652. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  56653. this._linkParameters();
  56654. };
  56655. PostProcessRenderEffect.prototype.getPass = function (passName) {
  56656. for (var renderPassName in this._renderPasses) {
  56657. if (renderPassName === passName) {
  56658. return this._renderPasses[passName];
  56659. }
  56660. }
  56661. return null;
  56662. };
  56663. PostProcessRenderEffect.prototype.emptyPasses = function () {
  56664. this._renderPasses = {};
  56665. this._linkParameters();
  56666. };
  56667. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  56668. var cameraKey;
  56669. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56670. if (!cams) {
  56671. return;
  56672. }
  56673. for (var i = 0; i < cams.length; i++) {
  56674. var camera = cams[i];
  56675. var cameraName = camera.name;
  56676. if (this._singleInstance) {
  56677. cameraKey = 0;
  56678. }
  56679. else {
  56680. cameraKey = cameraName;
  56681. }
  56682. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  56683. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  56684. if (!this._indicesForCamera[cameraName]) {
  56685. this._indicesForCamera[cameraName] = [];
  56686. }
  56687. this._indicesForCamera[cameraName].push(index);
  56688. if (!this._cameras[cameraName]) {
  56689. this._cameras[cameraName] = camera;
  56690. }
  56691. for (var passName in this._renderPasses) {
  56692. this._renderPasses[passName]._incRefCount();
  56693. }
  56694. }
  56695. this._linkParameters();
  56696. };
  56697. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  56698. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56699. if (!cams) {
  56700. return;
  56701. }
  56702. for (var i = 0; i < cams.length; i++) {
  56703. var camera = cams[i];
  56704. var cameraName = camera.name;
  56705. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56706. if (this._cameras[cameraName]) {
  56707. //this._indicesForCamera.splice(index, 1);
  56708. this._cameras[cameraName] = null;
  56709. }
  56710. for (var passName in this._renderPasses) {
  56711. this._renderPasses[passName]._decRefCount();
  56712. }
  56713. }
  56714. };
  56715. PostProcessRenderEffect.prototype._enable = function (cameras) {
  56716. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56717. if (!cams) {
  56718. return;
  56719. }
  56720. for (var i = 0; i < cams.length; i++) {
  56721. var camera = cams[i];
  56722. var cameraName = camera.name;
  56723. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  56724. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  56725. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  56726. }
  56727. }
  56728. for (var passName in this._renderPasses) {
  56729. this._renderPasses[passName]._incRefCount();
  56730. }
  56731. }
  56732. };
  56733. PostProcessRenderEffect.prototype._disable = function (cameras) {
  56734. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56735. if (!cams) {
  56736. return;
  56737. }
  56738. for (var i = 0; i < cams.length; i++) {
  56739. var camera = cams[i];
  56740. var cameraName = camera.Name;
  56741. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56742. for (var passName in this._renderPasses) {
  56743. this._renderPasses[passName]._decRefCount();
  56744. }
  56745. }
  56746. };
  56747. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  56748. if (this._singleInstance) {
  56749. return this._postProcesses[0];
  56750. }
  56751. else {
  56752. if (!camera) {
  56753. return null;
  56754. }
  56755. return this._postProcesses[camera.name];
  56756. }
  56757. };
  56758. PostProcessRenderEffect.prototype._linkParameters = function () {
  56759. var _this = this;
  56760. for (var index in this._postProcesses) {
  56761. if (this.applyParameters) {
  56762. this.applyParameters(this._postProcesses[index]);
  56763. }
  56764. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  56765. _this._linkTextures(effect);
  56766. });
  56767. }
  56768. };
  56769. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  56770. for (var renderPassName in this._renderPasses) {
  56771. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  56772. }
  56773. for (var renderEffectName in this._renderEffectAsPasses) {
  56774. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  56775. }
  56776. };
  56777. return PostProcessRenderEffect;
  56778. }());
  56779. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  56780. })(BABYLON || (BABYLON = {}));
  56781. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  56782. var BABYLON;
  56783. (function (BABYLON) {
  56784. var PostProcessRenderPipeline = /** @class */ (function () {
  56785. function PostProcessRenderPipeline(engine, name) {
  56786. this._engine = engine;
  56787. this._name = name;
  56788. this._renderEffects = {};
  56789. this._renderEffectsForIsolatedPass = new Array();
  56790. this._cameras = [];
  56791. }
  56792. PostProcessRenderPipeline.prototype.getClassName = function () {
  56793. return "PostProcessRenderPipeline";
  56794. };
  56795. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  56796. get: function () {
  56797. for (var renderEffectName in this._renderEffects) {
  56798. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56799. if (!this._renderEffects[renderEffectName].isSupported) {
  56800. return false;
  56801. }
  56802. }
  56803. }
  56804. return true;
  56805. },
  56806. enumerable: true,
  56807. configurable: true
  56808. });
  56809. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  56810. this._renderEffects[renderEffect._name] = renderEffect;
  56811. };
  56812. // private
  56813. PostProcessRenderPipeline.prototype._rebuild = function () {
  56814. };
  56815. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  56816. var renderEffects = this._renderEffects[renderEffectName];
  56817. if (!renderEffects) {
  56818. return;
  56819. }
  56820. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56821. };
  56822. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  56823. var renderEffects = this._renderEffects[renderEffectName];
  56824. if (!renderEffects) {
  56825. return;
  56826. }
  56827. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56828. };
  56829. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  56830. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56831. if (!cams) {
  56832. return;
  56833. }
  56834. var indicesToDelete = [];
  56835. var i;
  56836. for (i = 0; i < cams.length; i++) {
  56837. var camera = cams[i];
  56838. var cameraName = camera.name;
  56839. if (this._cameras.indexOf(camera) === -1) {
  56840. this._cameras[cameraName] = camera;
  56841. }
  56842. else if (unique) {
  56843. indicesToDelete.push(i);
  56844. }
  56845. }
  56846. for (i = 0; i < indicesToDelete.length; i++) {
  56847. cameras.splice(indicesToDelete[i], 1);
  56848. }
  56849. for (var renderEffectName in this._renderEffects) {
  56850. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56851. this._renderEffects[renderEffectName]._attachCameras(cams);
  56852. }
  56853. }
  56854. };
  56855. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  56856. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56857. if (!cams) {
  56858. return;
  56859. }
  56860. for (var renderEffectName in this._renderEffects) {
  56861. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56862. this._renderEffects[renderEffectName]._detachCameras(cams);
  56863. }
  56864. }
  56865. for (var i = 0; i < cams.length; i++) {
  56866. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  56867. }
  56868. };
  56869. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  56870. var _this = this;
  56871. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56872. if (!cams) {
  56873. return;
  56874. }
  56875. var pass = null;
  56876. var renderEffectName;
  56877. for (renderEffectName in this._renderEffects) {
  56878. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56879. pass = this._renderEffects[renderEffectName].getPass(passName);
  56880. if (pass != null) {
  56881. break;
  56882. }
  56883. }
  56884. }
  56885. if (pass === null) {
  56886. return;
  56887. }
  56888. for (renderEffectName in this._renderEffects) {
  56889. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56890. this._renderEffects[renderEffectName]._disable(cams);
  56891. }
  56892. }
  56893. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  56894. for (var i = 0; i < cams.length; i++) {
  56895. var camera = cams[i];
  56896. var cameraName = camera.name;
  56897. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  56898. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  56899. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  56900. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  56901. }
  56902. };
  56903. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  56904. var _this = this;
  56905. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56906. if (!cams) {
  56907. return;
  56908. }
  56909. for (var i = 0; i < cams.length; i++) {
  56910. var camera = cams[i];
  56911. var cameraName = camera.name;
  56912. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  56913. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  56914. }
  56915. for (var renderEffectName in this._renderEffects) {
  56916. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56917. this._renderEffects[renderEffectName]._enable(cams);
  56918. }
  56919. }
  56920. };
  56921. PostProcessRenderPipeline.prototype._update = function () {
  56922. for (var renderEffectName in this._renderEffects) {
  56923. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56924. this._renderEffects[renderEffectName]._update();
  56925. }
  56926. }
  56927. for (var i = 0; i < this._cameras.length; i++) {
  56928. var cameraName = this._cameras[i].name;
  56929. if (this._renderEffectsForIsolatedPass[cameraName]) {
  56930. this._renderEffectsForIsolatedPass[cameraName]._update();
  56931. }
  56932. }
  56933. };
  56934. PostProcessRenderPipeline.prototype._reset = function () {
  56935. this._renderEffects = {};
  56936. this._renderEffectsForIsolatedPass = new Array();
  56937. };
  56938. PostProcessRenderPipeline.prototype.dispose = function () {
  56939. // Must be implemented by children
  56940. };
  56941. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  56942. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  56943. __decorate([
  56944. BABYLON.serialize()
  56945. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  56946. return PostProcessRenderPipeline;
  56947. }());
  56948. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  56949. })(BABYLON || (BABYLON = {}));
  56950. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  56951. var BABYLON;
  56952. (function (BABYLON) {
  56953. var DepthRenderer = /** @class */ (function () {
  56954. function DepthRenderer(scene, type) {
  56955. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  56956. var _this = this;
  56957. this._scene = scene;
  56958. var engine = scene.getEngine();
  56959. // Render target
  56960. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  56961. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56962. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56963. this._depthMap.refreshRate = 1;
  56964. this._depthMap.renderParticles = false;
  56965. this._depthMap.renderList = null;
  56966. // set default depth value to 1.0 (far away)
  56967. this._depthMap.onClearObservable.add(function (engine) {
  56968. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56969. });
  56970. // Custom render function
  56971. var renderSubMesh = function (subMesh) {
  56972. var mesh = subMesh.getRenderingMesh();
  56973. var scene = _this._scene;
  56974. var engine = scene.getEngine();
  56975. var material = subMesh.getMaterial();
  56976. if (!material) {
  56977. return;
  56978. }
  56979. // Culling
  56980. engine.setState(material.backFaceCulling);
  56981. // Managing instances
  56982. var batch = mesh._getInstancesRenderList(subMesh._id);
  56983. if (batch.mustReturn) {
  56984. return;
  56985. }
  56986. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  56987. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  56988. engine.enableEffect(_this._effect);
  56989. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  56990. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  56991. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  56992. // Alpha test
  56993. if (material && material.needAlphaTesting()) {
  56994. var alphaTexture = material.getAlphaTestTexture();
  56995. if (alphaTexture) {
  56996. _this._effect.setTexture("diffuseSampler", alphaTexture);
  56997. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  56998. }
  56999. }
  57000. // Bones
  57001. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57002. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57003. }
  57004. // Draw
  57005. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57006. }
  57007. };
  57008. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57009. var index;
  57010. if (depthOnlySubMeshes.length) {
  57011. engine.setColorWrite(false);
  57012. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57013. renderSubMesh(depthOnlySubMeshes.data[index]);
  57014. }
  57015. engine.setColorWrite(true);
  57016. }
  57017. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57018. renderSubMesh(opaqueSubMeshes.data[index]);
  57019. }
  57020. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57021. renderSubMesh(alphaTestSubMeshes.data[index]);
  57022. }
  57023. };
  57024. }
  57025. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  57026. var material = subMesh.getMaterial();
  57027. if (material.disableDepthWrite) {
  57028. return false;
  57029. }
  57030. var defines = [];
  57031. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57032. var mesh = subMesh.getMesh();
  57033. // Alpha test
  57034. if (material && material.needAlphaTesting()) {
  57035. defines.push("#define ALPHATEST");
  57036. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57037. attribs.push(BABYLON.VertexBuffer.UVKind);
  57038. defines.push("#define UV1");
  57039. }
  57040. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57041. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57042. defines.push("#define UV2");
  57043. }
  57044. }
  57045. // Bones
  57046. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57047. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57048. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57049. if (mesh.numBoneInfluencers > 4) {
  57050. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57051. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57052. }
  57053. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57054. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  57055. }
  57056. else {
  57057. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57058. }
  57059. // Instances
  57060. if (useInstances) {
  57061. defines.push("#define INSTANCES");
  57062. attribs.push("world0");
  57063. attribs.push("world1");
  57064. attribs.push("world2");
  57065. attribs.push("world3");
  57066. }
  57067. // Get correct effect
  57068. var join = defines.join("\n");
  57069. if (this._cachedDefines !== join) {
  57070. this._cachedDefines = join;
  57071. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  57072. }
  57073. return this._effect.isReady();
  57074. };
  57075. DepthRenderer.prototype.getDepthMap = function () {
  57076. return this._depthMap;
  57077. };
  57078. // Methods
  57079. DepthRenderer.prototype.dispose = function () {
  57080. this._depthMap.dispose();
  57081. };
  57082. return DepthRenderer;
  57083. }());
  57084. BABYLON.DepthRenderer = DepthRenderer;
  57085. })(BABYLON || (BABYLON = {}));
  57086. //# sourceMappingURL=babylon.depthRenderer.js.map
  57087. var BABYLON;
  57088. (function (BABYLON) {
  57089. var SSAORenderingPipeline = /** @class */ (function (_super) {
  57090. __extends(SSAORenderingPipeline, _super);
  57091. /**
  57092. * @constructor
  57093. * @param {string} name - The rendering pipeline name
  57094. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57095. * @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 }
  57096. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57097. */
  57098. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  57099. var _this = _super.call(this, scene.getEngine(), name) || this;
  57100. // Members
  57101. /**
  57102. * The PassPostProcess id in the pipeline that contains the original scene color
  57103. * @type {string}
  57104. */
  57105. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57106. /**
  57107. * The SSAO PostProcess id in the pipeline
  57108. * @type {string}
  57109. */
  57110. _this.SSAORenderEffect = "SSAORenderEffect";
  57111. /**
  57112. * The horizontal blur PostProcess id in the pipeline
  57113. * @type {string}
  57114. */
  57115. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57116. /**
  57117. * The vertical blur PostProcess id in the pipeline
  57118. * @type {string}
  57119. */
  57120. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57121. /**
  57122. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57123. * @type {string}
  57124. */
  57125. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57126. /**
  57127. * The output strength of the SSAO post-process. Default value is 1.0.
  57128. * @type {number}
  57129. */
  57130. _this.totalStrength = 1.0;
  57131. /**
  57132. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  57133. * @type {number}
  57134. */
  57135. _this.radius = 0.0001;
  57136. /**
  57137. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  57138. * Must not be equal to fallOff and superior to fallOff.
  57139. * Default value is 0.975
  57140. * @type {number}
  57141. */
  57142. _this.area = 0.0075;
  57143. /**
  57144. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  57145. * Must not be equal to area and inferior to area.
  57146. * Default value is 0.0
  57147. * @type {number}
  57148. */
  57149. _this.fallOff = 0.000001;
  57150. /**
  57151. * The base color of the SSAO post-process
  57152. * The final result is "base + ssao" between [0, 1]
  57153. * @type {number}
  57154. */
  57155. _this.base = 0.5;
  57156. _this._firstUpdate = true;
  57157. _this._scene = scene;
  57158. // Set up assets
  57159. _this._createRandomTexture();
  57160. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57161. var ssaoRatio = ratio.ssaoRatio || ratio;
  57162. var combineRatio = ratio.combineRatio || ratio;
  57163. _this._ratio = {
  57164. ssaoRatio: ssaoRatio,
  57165. combineRatio: combineRatio
  57166. };
  57167. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57168. _this._createSSAOPostProcess(ssaoRatio);
  57169. _this._createBlurPostProcess(ssaoRatio);
  57170. _this._createSSAOCombinePostProcess(combineRatio);
  57171. // Set up pipeline
  57172. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57173. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57174. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57175. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57176. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57177. // Finish
  57178. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57179. if (cameras)
  57180. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57181. return _this;
  57182. }
  57183. // Public Methods
  57184. /**
  57185. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57186. */
  57187. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57188. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57189. for (var i = 0; i < this._scene.cameras.length; i++) {
  57190. var camera = this._scene.cameras[i];
  57191. this._originalColorPostProcess.dispose(camera);
  57192. this._ssaoPostProcess.dispose(camera);
  57193. this._blurHPostProcess.dispose(camera);
  57194. this._blurVPostProcess.dispose(camera);
  57195. this._ssaoCombinePostProcess.dispose(camera);
  57196. }
  57197. this._randomTexture.dispose();
  57198. if (disableDepthRender)
  57199. this._scene.disableDepthRenderer();
  57200. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57201. _super.prototype.dispose.call(this);
  57202. };
  57203. // Private Methods
  57204. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  57205. var _this = this;
  57206. /*
  57207. var samplerOffsets = [
  57208. -8.0, -6.0, -4.0, -2.0,
  57209. 0.0,
  57210. 2.0, 4.0, 6.0, 8.0
  57211. ];
  57212. */
  57213. var samplerOffsets = new Array();
  57214. for (var i = -8; i < 8; i++) {
  57215. samplerOffsets.push(i * 2);
  57216. }
  57217. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  57218. this._blurHPostProcess.onApply = function (effect) {
  57219. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57220. effect.setTexture("depthSampler", _this._depthTexture);
  57221. if (_this._firstUpdate) {
  57222. effect.setArray("samplerOffsets", samplerOffsets);
  57223. }
  57224. };
  57225. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  57226. this._blurVPostProcess.onApply = function (effect) {
  57227. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57228. effect.setTexture("depthSampler", _this._depthTexture);
  57229. if (_this._firstUpdate) {
  57230. effect.setArray("samplerOffsets", samplerOffsets);
  57231. _this._firstUpdate = false;
  57232. }
  57233. };
  57234. };
  57235. SSAORenderingPipeline.prototype._rebuild = function () {
  57236. this._firstUpdate = true;
  57237. _super.prototype._rebuild.call(this);
  57238. };
  57239. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57240. var _this = this;
  57241. var numSamples = 16;
  57242. var sampleSphere = [
  57243. 0.5381, 0.1856, -0.4319,
  57244. 0.1379, 0.2486, 0.4430,
  57245. 0.3371, 0.5679, -0.0057,
  57246. -0.6999, -0.0451, -0.0019,
  57247. 0.0689, -0.1598, -0.8547,
  57248. 0.0560, 0.0069, -0.1843,
  57249. -0.0146, 0.1402, 0.0762,
  57250. 0.0100, -0.1924, -0.0344,
  57251. -0.3577, -0.5301, -0.4358,
  57252. -0.3169, 0.1063, 0.0158,
  57253. 0.0103, -0.5869, 0.0046,
  57254. -0.0897, -0.4940, 0.3287,
  57255. 0.7119, -0.0154, -0.0918,
  57256. -0.0533, 0.0596, -0.5411,
  57257. 0.0352, -0.0631, 0.5460,
  57258. -0.4776, 0.2847, -0.0271
  57259. ];
  57260. var samplesFactor = 1.0 / numSamples;
  57261. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  57262. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57263. "area", "fallOff", "base", "range", "viewport"
  57264. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57265. this._ssaoPostProcess.onApply = function (effect) {
  57266. if (_this._firstUpdate) {
  57267. effect.setArray3("sampleSphere", sampleSphere);
  57268. effect.setFloat("samplesFactor", samplesFactor);
  57269. effect.setFloat("randTextureTiles", 4.0);
  57270. }
  57271. effect.setFloat("totalStrength", _this.totalStrength);
  57272. effect.setFloat("radius", _this.radius);
  57273. effect.setFloat("area", _this.area);
  57274. effect.setFloat("fallOff", _this.fallOff);
  57275. effect.setFloat("base", _this.base);
  57276. effect.setTexture("textureSampler", _this._depthTexture);
  57277. effect.setTexture("randomSampler", _this._randomTexture);
  57278. };
  57279. };
  57280. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57281. var _this = this;
  57282. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57283. this._ssaoCombinePostProcess.onApply = function (effect) {
  57284. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57285. };
  57286. };
  57287. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  57288. var size = 512;
  57289. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57290. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57291. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57292. var context = this._randomTexture.getContext();
  57293. var rand = function (min, max) {
  57294. return Math.random() * (max - min) + min;
  57295. };
  57296. var randVector = BABYLON.Vector3.Zero();
  57297. for (var x = 0; x < size; x++) {
  57298. for (var y = 0; y < size; y++) {
  57299. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  57300. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  57301. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  57302. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57303. context.fillRect(x, y, 1, 1);
  57304. }
  57305. }
  57306. this._randomTexture.update(false);
  57307. };
  57308. __decorate([
  57309. BABYLON.serialize()
  57310. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  57311. __decorate([
  57312. BABYLON.serialize()
  57313. ], SSAORenderingPipeline.prototype, "radius", void 0);
  57314. __decorate([
  57315. BABYLON.serialize()
  57316. ], SSAORenderingPipeline.prototype, "area", void 0);
  57317. __decorate([
  57318. BABYLON.serialize()
  57319. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  57320. __decorate([
  57321. BABYLON.serialize()
  57322. ], SSAORenderingPipeline.prototype, "base", void 0);
  57323. __decorate([
  57324. BABYLON.serialize()
  57325. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  57326. return SSAORenderingPipeline;
  57327. }(BABYLON.PostProcessRenderPipeline));
  57328. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  57329. })(BABYLON || (BABYLON = {}));
  57330. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  57331. var BABYLON;
  57332. (function (BABYLON) {
  57333. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  57334. __extends(SSAO2RenderingPipeline, _super);
  57335. /**
  57336. * @constructor
  57337. * @param {string} name - The rendering pipeline name
  57338. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57339. * @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 }
  57340. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57341. */
  57342. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  57343. var _this = _super.call(this, scene.getEngine(), name) || this;
  57344. // Members
  57345. /**
  57346. * The PassPostProcess id in the pipeline that contains the original scene color
  57347. * @type {string}
  57348. */
  57349. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57350. /**
  57351. * The SSAO PostProcess id in the pipeline
  57352. * @type {string}
  57353. */
  57354. _this.SSAORenderEffect = "SSAORenderEffect";
  57355. /**
  57356. * The horizontal blur PostProcess id in the pipeline
  57357. * @type {string}
  57358. */
  57359. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57360. /**
  57361. * The vertical blur PostProcess id in the pipeline
  57362. * @type {string}
  57363. */
  57364. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57365. /**
  57366. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57367. * @type {string}
  57368. */
  57369. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57370. /**
  57371. * The output strength of the SSAO post-process. Default value is 1.0.
  57372. * @type {number}
  57373. */
  57374. _this.totalStrength = 1.0;
  57375. /**
  57376. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  57377. * @type {number}
  57378. */
  57379. _this.maxZ = 100.0;
  57380. /**
  57381. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  57382. * @type {number}
  57383. */
  57384. _this.minZAspect = 0.2;
  57385. /**
  57386. * Number of samples used for the SSAO calculations. Default value is 8
  57387. * @type {number}
  57388. */
  57389. _this._samples = 8;
  57390. /**
  57391. * Are we using bilateral blur ?
  57392. * @type {boolean}
  57393. */
  57394. _this._expensiveBlur = true;
  57395. /**
  57396. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  57397. * @type {number}
  57398. */
  57399. _this.radius = 2.0;
  57400. /**
  57401. * The base color of the SSAO post-process
  57402. * The final result is "base + ssao" between [0, 1]
  57403. * @type {number}
  57404. */
  57405. _this.base = 0.1;
  57406. _this._firstUpdate = true;
  57407. _this._scene = scene;
  57408. if (!_this.isSupported) {
  57409. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  57410. return _this;
  57411. }
  57412. var ssaoRatio = ratio.ssaoRatio || ratio;
  57413. var blurRatio = ratio.blurRatio || ratio;
  57414. _this._ratio = {
  57415. ssaoRatio: ssaoRatio,
  57416. blurRatio: blurRatio
  57417. };
  57418. // Set up assets
  57419. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  57420. _this._createRandomTexture();
  57421. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  57422. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  57423. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57424. _this._createSSAOPostProcess(1.0);
  57425. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  57426. _this._createSSAOCombinePostProcess(blurRatio);
  57427. // Set up pipeline
  57428. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57429. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57430. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57431. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57432. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57433. // Finish
  57434. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57435. if (cameras)
  57436. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57437. return _this;
  57438. }
  57439. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  57440. get: function () {
  57441. return this._samples;
  57442. },
  57443. set: function (n) {
  57444. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  57445. this._samples = n;
  57446. this._sampleSphere = this._generateHemisphere();
  57447. this._firstUpdate = true;
  57448. },
  57449. enumerable: true,
  57450. configurable: true
  57451. });
  57452. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  57453. get: function () {
  57454. return this._expensiveBlur;
  57455. },
  57456. set: function (b) {
  57457. 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"]);
  57458. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  57459. this._expensiveBlur = b;
  57460. this._firstUpdate = true;
  57461. },
  57462. enumerable: true,
  57463. configurable: true
  57464. });
  57465. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  57466. /**
  57467. * Support test.
  57468. * @type {boolean}
  57469. */
  57470. get: function () {
  57471. var engine = BABYLON.Engine.LastCreatedEngine;
  57472. if (!engine) {
  57473. return false;
  57474. }
  57475. return engine.getCaps().drawBuffersExtension;
  57476. },
  57477. enumerable: true,
  57478. configurable: true
  57479. });
  57480. // Public Methods
  57481. /**
  57482. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57483. */
  57484. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  57485. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  57486. for (var i = 0; i < this._scene.cameras.length; i++) {
  57487. var camera = this._scene.cameras[i];
  57488. this._originalColorPostProcess.dispose(camera);
  57489. this._ssaoPostProcess.dispose(camera);
  57490. this._blurHPostProcess.dispose(camera);
  57491. this._blurVPostProcess.dispose(camera);
  57492. this._ssaoCombinePostProcess.dispose(camera);
  57493. }
  57494. this._randomTexture.dispose();
  57495. if (disableGeometryBufferRenderer)
  57496. this._scene.disableGeometryBufferRenderer();
  57497. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57498. _super.prototype.dispose.call(this);
  57499. };
  57500. // Private Methods
  57501. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  57502. var _this = this;
  57503. this._samplerOffsets = [];
  57504. var expensive = this.expensiveBlur;
  57505. for (var i = -8; i < 8; i++) {
  57506. this._samplerOffsets.push(i * 2 + 0.5);
  57507. }
  57508. 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");
  57509. this._blurHPostProcess.onApply = function (effect) {
  57510. if (!_this._scene.activeCamera) {
  57511. return;
  57512. }
  57513. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57514. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57515. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57516. effect.setFloat("radius", _this.radius);
  57517. effect.setTexture("depthSampler", _this._depthTexture);
  57518. if (_this._firstUpdate) {
  57519. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57520. }
  57521. };
  57522. 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");
  57523. this._blurVPostProcess.onApply = function (effect) {
  57524. if (!_this._scene.activeCamera) {
  57525. return;
  57526. }
  57527. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57528. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57529. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57530. effect.setFloat("radius", _this.radius);
  57531. effect.setTexture("depthSampler", _this._depthTexture);
  57532. if (_this._firstUpdate) {
  57533. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57534. _this._firstUpdate = false;
  57535. }
  57536. };
  57537. };
  57538. SSAO2RenderingPipeline.prototype._rebuild = function () {
  57539. this._firstUpdate = true;
  57540. _super.prototype._rebuild.call(this);
  57541. };
  57542. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  57543. var numSamples = this.samples;
  57544. var result = [];
  57545. var vector, scale;
  57546. var rand = function (min, max) {
  57547. return Math.random() * (max - min) + min;
  57548. };
  57549. var i = 0;
  57550. while (i < numSamples) {
  57551. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  57552. vector.normalize();
  57553. scale = i / numSamples;
  57554. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  57555. vector.scaleInPlace(scale);
  57556. result.push(vector.x, vector.y, vector.z);
  57557. i++;
  57558. }
  57559. return result;
  57560. };
  57561. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57562. var _this = this;
  57563. var numSamples = this.samples;
  57564. this._sampleSphere = this._generateHemisphere();
  57565. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  57566. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57567. "base", "range", "projection", "near", "far", "texelSize",
  57568. "xViewport", "yViewport", "maxZ", "minZAspect"
  57569. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57570. this._ssaoPostProcess.onApply = function (effect) {
  57571. if (_this._firstUpdate) {
  57572. effect.setArray3("sampleSphere", _this._sampleSphere);
  57573. effect.setFloat("randTextureTiles", 4.0);
  57574. }
  57575. if (!_this._scene.activeCamera) {
  57576. return;
  57577. }
  57578. effect.setFloat("samplesFactor", 1 / _this.samples);
  57579. effect.setFloat("totalStrength", _this.totalStrength);
  57580. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  57581. effect.setFloat("radius", _this.radius);
  57582. effect.setFloat("maxZ", _this.maxZ);
  57583. effect.setFloat("minZAspect", _this.minZAspect);
  57584. effect.setFloat("base", _this.base);
  57585. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57586. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57587. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  57588. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  57589. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  57590. effect.setTexture("textureSampler", _this._depthTexture);
  57591. effect.setTexture("normalSampler", _this._normalTexture);
  57592. effect.setTexture("randomSampler", _this._randomTexture);
  57593. };
  57594. };
  57595. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57596. var _this = this;
  57597. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57598. this._ssaoCombinePostProcess.onApply = function (effect) {
  57599. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57600. };
  57601. };
  57602. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  57603. var size = 512;
  57604. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57605. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57606. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57607. var context = this._randomTexture.getContext();
  57608. var rand = function (min, max) {
  57609. return Math.random() * (max - min) + min;
  57610. };
  57611. var randVector = BABYLON.Vector3.Zero();
  57612. for (var x = 0; x < size; x++) {
  57613. for (var y = 0; y < size; y++) {
  57614. randVector.x = rand(0.0, 1.0);
  57615. randVector.y = rand(0.0, 1.0);
  57616. randVector.z = 0.0;
  57617. randVector.normalize();
  57618. randVector.scaleInPlace(255);
  57619. randVector.x = Math.floor(randVector.x);
  57620. randVector.y = Math.floor(randVector.y);
  57621. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57622. context.fillRect(x, y, 1, 1);
  57623. }
  57624. }
  57625. this._randomTexture.update(false);
  57626. };
  57627. __decorate([
  57628. BABYLON.serialize()
  57629. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  57630. __decorate([
  57631. BABYLON.serialize()
  57632. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  57633. __decorate([
  57634. BABYLON.serialize()
  57635. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  57636. __decorate([
  57637. BABYLON.serialize("samples")
  57638. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  57639. __decorate([
  57640. BABYLON.serialize("expensiveBlur")
  57641. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  57642. __decorate([
  57643. BABYLON.serialize()
  57644. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  57645. __decorate([
  57646. BABYLON.serialize()
  57647. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  57648. __decorate([
  57649. BABYLON.serialize()
  57650. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  57651. return SSAO2RenderingPipeline;
  57652. }(BABYLON.PostProcessRenderPipeline));
  57653. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  57654. })(BABYLON || (BABYLON = {}));
  57655. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  57656. // BABYLON.JS Chromatic Aberration GLSL Shader
  57657. // Author: Olivier Guyot
  57658. // Separates very slightly R, G and B colors on the edges of the screen
  57659. // Inspired by Francois Tarlier & Martins Upitis
  57660. var BABYLON;
  57661. (function (BABYLON) {
  57662. var LensRenderingPipeline = /** @class */ (function (_super) {
  57663. __extends(LensRenderingPipeline, _super);
  57664. /**
  57665. * @constructor
  57666. *
  57667. * Effect parameters are as follow:
  57668. * {
  57669. * chromatic_aberration: number; // from 0 to x (1 for realism)
  57670. * edge_blur: number; // from 0 to x (1 for realism)
  57671. * distortion: number; // from 0 to x (1 for realism)
  57672. * grain_amount: number; // from 0 to 1
  57673. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  57674. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  57675. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  57676. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  57677. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  57678. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  57679. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  57680. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  57681. * }
  57682. * Note: if an effect parameter is unset, effect is disabled
  57683. *
  57684. * @param {string} name - The rendering pipeline name
  57685. * @param {object} parameters - An object containing all parameters (see above)
  57686. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57687. * @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)
  57688. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57689. */
  57690. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  57691. if (ratio === void 0) { ratio = 1.0; }
  57692. var _this = _super.call(this, scene.getEngine(), name) || this;
  57693. // Lens effects can be of the following:
  57694. // - chromatic aberration (slight shift of RGB colors)
  57695. // - blur on the edge of the lens
  57696. // - lens distortion
  57697. // - depth-of-field blur & highlights enhancing
  57698. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  57699. // - grain effect (noise or custom texture)
  57700. // Two additional texture samplers are needed:
  57701. // - depth map (for depth-of-field)
  57702. // - grain texture
  57703. /**
  57704. * The chromatic aberration PostProcess id in the pipeline
  57705. * @type {string}
  57706. */
  57707. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  57708. /**
  57709. * The highlights enhancing PostProcess id in the pipeline
  57710. * @type {string}
  57711. */
  57712. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  57713. /**
  57714. * The depth-of-field PostProcess id in the pipeline
  57715. * @type {string}
  57716. */
  57717. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  57718. _this._scene = scene;
  57719. // Fetch texture samplers
  57720. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57721. if (parameters.grain_texture) {
  57722. _this._grainTexture = parameters.grain_texture;
  57723. }
  57724. else {
  57725. _this._createGrainTexture();
  57726. }
  57727. // save parameters
  57728. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  57729. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  57730. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  57731. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  57732. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  57733. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  57734. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  57735. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  57736. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  57737. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  57738. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  57739. // Create effects
  57740. _this._createChromaticAberrationPostProcess(ratio);
  57741. _this._createHighlightsPostProcess(ratio);
  57742. _this._createDepthOfFieldPostProcess(ratio / 4);
  57743. // Set up pipeline
  57744. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  57745. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  57746. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  57747. if (_this._highlightsGain === -1) {
  57748. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  57749. }
  57750. // Finish
  57751. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57752. if (cameras) {
  57753. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57754. }
  57755. return _this;
  57756. }
  57757. // public methods (self explanatory)
  57758. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  57759. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  57760. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  57761. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  57762. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  57763. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  57764. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  57765. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  57766. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  57767. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  57768. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  57769. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  57770. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  57771. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  57772. };
  57773. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  57774. this._highlightsPostProcess.updateEffect();
  57775. };
  57776. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  57777. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  57778. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  57779. this._highlightsGain = amount;
  57780. };
  57781. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  57782. if (this._highlightsGain === -1) {
  57783. this._highlightsGain = 1.0;
  57784. }
  57785. this._highlightsThreshold = amount;
  57786. };
  57787. LensRenderingPipeline.prototype.disableHighlights = function () {
  57788. this._highlightsGain = -1;
  57789. };
  57790. /**
  57791. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  57792. */
  57793. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57794. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57795. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57796. this._chromaticAberrationPostProcess = null;
  57797. this._highlightsPostProcess = null;
  57798. this._depthOfFieldPostProcess = null;
  57799. this._grainTexture.dispose();
  57800. if (disableDepthRender)
  57801. this._scene.disableDepthRenderer();
  57802. };
  57803. // colors shifting and distortion
  57804. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  57805. var _this = this;
  57806. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  57807. [], // samplers
  57808. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57809. this._chromaticAberrationPostProcess.onApply = function (effect) {
  57810. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  57811. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57812. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57813. };
  57814. };
  57815. // highlights enhancing
  57816. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  57817. var _this = this;
  57818. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  57819. [], // samplers
  57820. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  57821. this._highlightsPostProcess.onApply = function (effect) {
  57822. effect.setFloat('gain', _this._highlightsGain);
  57823. effect.setFloat('threshold', _this._highlightsThreshold);
  57824. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  57825. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57826. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57827. };
  57828. };
  57829. // colors shifting and distortion
  57830. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  57831. var _this = this;
  57832. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  57833. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  57834. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  57835. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57836. this._depthOfFieldPostProcess.onApply = function (effect) {
  57837. effect.setTexture("depthSampler", _this._depthTexture);
  57838. effect.setTexture("grainSampler", _this._grainTexture);
  57839. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  57840. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  57841. effect.setFloat('grain_amount', _this._grainAmount);
  57842. effect.setBool('blur_noise', _this._blurNoise);
  57843. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57844. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57845. effect.setFloat('distortion', _this._distortion);
  57846. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  57847. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  57848. effect.setFloat('aperture', _this._dofAperture);
  57849. effect.setFloat('darken', _this._dofDarken);
  57850. effect.setFloat('edge_blur', _this._edgeBlur);
  57851. effect.setBool('highlights', (_this._highlightsGain !== -1));
  57852. if (_this._scene.activeCamera) {
  57853. effect.setFloat('near', _this._scene.activeCamera.minZ);
  57854. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  57855. }
  57856. };
  57857. };
  57858. // creates a black and white random noise texture, 512x512
  57859. LensRenderingPipeline.prototype._createGrainTexture = function () {
  57860. var size = 512;
  57861. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57862. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57863. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57864. var context = this._grainTexture.getContext();
  57865. var rand = function (min, max) {
  57866. return Math.random() * (max - min) + min;
  57867. };
  57868. var value;
  57869. for (var x = 0; x < size; x++) {
  57870. for (var y = 0; y < size; y++) {
  57871. value = Math.floor(rand(0.42, 0.58) * 255);
  57872. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  57873. context.fillRect(x, y, 1, 1);
  57874. }
  57875. }
  57876. this._grainTexture.update(false);
  57877. };
  57878. return LensRenderingPipeline;
  57879. }(BABYLON.PostProcessRenderPipeline));
  57880. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  57881. })(BABYLON || (BABYLON = {}));
  57882. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  57883. var BABYLON;
  57884. (function (BABYLON) {
  57885. var StandardRenderingPipeline = /** @class */ (function (_super) {
  57886. __extends(StandardRenderingPipeline, _super);
  57887. /**
  57888. * @constructor
  57889. * @param {string} name - The rendering pipeline name
  57890. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57891. * @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)
  57892. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  57893. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57894. */
  57895. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  57896. if (originalPostProcess === void 0) { originalPostProcess = null; }
  57897. var _this = _super.call(this, scene.getEngine(), name) || this;
  57898. _this.downSampleX4PostProcess = null;
  57899. _this.brightPassPostProcess = null;
  57900. _this.blurHPostProcesses = [];
  57901. _this.blurVPostProcesses = [];
  57902. _this.textureAdderPostProcess = null;
  57903. _this.volumetricLightPostProcess = null;
  57904. _this.volumetricLightSmoothXPostProcess = null;
  57905. _this.volumetricLightSmoothYPostProcess = null;
  57906. _this.volumetricLightMergePostProces = null;
  57907. _this.volumetricLightFinalPostProcess = null;
  57908. _this.luminancePostProcess = null;
  57909. _this.luminanceDownSamplePostProcesses = [];
  57910. _this.hdrPostProcess = null;
  57911. _this.textureAdderFinalPostProcess = null;
  57912. _this.lensFlareFinalPostProcess = null;
  57913. _this.hdrFinalPostProcess = null;
  57914. _this.lensFlarePostProcess = null;
  57915. _this.lensFlareComposePostProcess = null;
  57916. _this.motionBlurPostProcess = null;
  57917. _this.depthOfFieldPostProcess = null;
  57918. // Values
  57919. _this.brightThreshold = 1.0;
  57920. _this.blurWidth = 512.0;
  57921. _this.horizontalBlur = false;
  57922. _this.exposure = 1.0;
  57923. _this.lensTexture = null;
  57924. _this.volumetricLightCoefficient = 0.2;
  57925. _this.volumetricLightPower = 4.0;
  57926. _this.volumetricLightBlurScale = 64.0;
  57927. _this.sourceLight = null;
  57928. _this.hdrMinimumLuminance = 1.0;
  57929. _this.hdrDecreaseRate = 0.5;
  57930. _this.hdrIncreaseRate = 0.5;
  57931. _this.lensColorTexture = null;
  57932. _this.lensFlareStrength = 20.0;
  57933. _this.lensFlareGhostDispersal = 1.4;
  57934. _this.lensFlareHaloWidth = 0.7;
  57935. _this.lensFlareDistortionStrength = 16.0;
  57936. _this.lensStarTexture = null;
  57937. _this.lensFlareDirtTexture = null;
  57938. _this.depthOfFieldDistance = 10.0;
  57939. _this.depthOfFieldBlurWidth = 64.0;
  57940. _this.motionStrength = 1.0;
  57941. // IAnimatable
  57942. _this.animations = [];
  57943. _this._currentDepthOfFieldSource = null;
  57944. _this._hdrCurrentLuminance = 1.0;
  57945. // Getters and setters
  57946. _this._bloomEnabled = true;
  57947. _this._depthOfFieldEnabled = false;
  57948. _this._vlsEnabled = false;
  57949. _this._lensFlareEnabled = false;
  57950. _this._hdrEnabled = false;
  57951. _this._motionBlurEnabled = false;
  57952. _this._motionBlurSamples = 64.0;
  57953. _this._volumetricLightStepsCount = 50.0;
  57954. _this._cameras = cameras || [];
  57955. // Initialize
  57956. _this._scene = scene;
  57957. _this._basePostProcess = originalPostProcess;
  57958. _this._ratio = ratio;
  57959. // Misc
  57960. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57961. // Finish
  57962. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57963. _this._buildPipeline();
  57964. return _this;
  57965. }
  57966. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  57967. get: function () {
  57968. return this._bloomEnabled;
  57969. },
  57970. set: function (enabled) {
  57971. if (this._bloomEnabled === enabled) {
  57972. return;
  57973. }
  57974. this._bloomEnabled = enabled;
  57975. this._buildPipeline();
  57976. },
  57977. enumerable: true,
  57978. configurable: true
  57979. });
  57980. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  57981. get: function () {
  57982. return this._depthOfFieldEnabled;
  57983. },
  57984. set: function (enabled) {
  57985. if (this._depthOfFieldEnabled === enabled) {
  57986. return;
  57987. }
  57988. this._depthOfFieldEnabled = enabled;
  57989. this._buildPipeline();
  57990. },
  57991. enumerable: true,
  57992. configurable: true
  57993. });
  57994. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  57995. get: function () {
  57996. return this._lensFlareEnabled;
  57997. },
  57998. set: function (enabled) {
  57999. if (this._lensFlareEnabled === enabled) {
  58000. return;
  58001. }
  58002. this._lensFlareEnabled = enabled;
  58003. this._buildPipeline();
  58004. },
  58005. enumerable: true,
  58006. configurable: true
  58007. });
  58008. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  58009. get: function () {
  58010. return this._hdrEnabled;
  58011. },
  58012. set: function (enabled) {
  58013. if (this._hdrEnabled === enabled) {
  58014. return;
  58015. }
  58016. this._hdrEnabled = enabled;
  58017. this._buildPipeline();
  58018. },
  58019. enumerable: true,
  58020. configurable: true
  58021. });
  58022. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  58023. get: function () {
  58024. return this._vlsEnabled;
  58025. },
  58026. set: function (enabled) {
  58027. if (this._vlsEnabled === enabled) {
  58028. return;
  58029. }
  58030. if (enabled) {
  58031. var geometry = this._scene.enableGeometryBufferRenderer();
  58032. if (!geometry) {
  58033. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  58034. return;
  58035. }
  58036. }
  58037. this._vlsEnabled = enabled;
  58038. this._buildPipeline();
  58039. },
  58040. enumerable: true,
  58041. configurable: true
  58042. });
  58043. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  58044. get: function () {
  58045. return this._motionBlurEnabled;
  58046. },
  58047. set: function (enabled) {
  58048. if (this._motionBlurEnabled === enabled) {
  58049. return;
  58050. }
  58051. this._motionBlurEnabled = enabled;
  58052. this._buildPipeline();
  58053. },
  58054. enumerable: true,
  58055. configurable: true
  58056. });
  58057. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  58058. get: function () {
  58059. return this._volumetricLightStepsCount;
  58060. },
  58061. set: function (count) {
  58062. if (this.volumetricLightPostProcess) {
  58063. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  58064. }
  58065. this._volumetricLightStepsCount = count;
  58066. },
  58067. enumerable: true,
  58068. configurable: true
  58069. });
  58070. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  58071. get: function () {
  58072. return this._motionBlurSamples;
  58073. },
  58074. set: function (samples) {
  58075. if (this.motionBlurPostProcess) {
  58076. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  58077. }
  58078. this._motionBlurSamples = samples;
  58079. },
  58080. enumerable: true,
  58081. configurable: true
  58082. });
  58083. StandardRenderingPipeline.prototype._buildPipeline = function () {
  58084. var _this = this;
  58085. var ratio = this._ratio;
  58086. var scene = this._scene;
  58087. this._disposePostProcesses();
  58088. this._reset();
  58089. // Create pass post-process
  58090. if (!this._basePostProcess) {
  58091. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  58092. this.originalPostProcess.onApply = function (effect) {
  58093. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  58094. };
  58095. }
  58096. else {
  58097. this.originalPostProcess = this._basePostProcess;
  58098. }
  58099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  58100. this._currentDepthOfFieldSource = this.originalPostProcess;
  58101. if (this._vlsEnabled) {
  58102. // Create volumetric light
  58103. this._createVolumetricLightPostProcess(scene, ratio);
  58104. // Create volumetric light final post-process
  58105. 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);
  58106. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  58107. }
  58108. if (this._bloomEnabled) {
  58109. // Create down sample X4 post-process
  58110. this._createDownSampleX4PostProcess(scene, ratio / 2);
  58111. // Create bright pass post-process
  58112. this._createBrightPassPostProcess(scene, ratio / 2);
  58113. // Create gaussian blur post-processes (down sampling blurs)
  58114. this._createBlurPostProcesses(scene, ratio / 4, 1);
  58115. // Create texture adder post-process
  58116. this._createTextureAdderPostProcess(scene, ratio);
  58117. // Create depth-of-field source post-process
  58118. 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);
  58119. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  58120. }
  58121. if (this._lensFlareEnabled) {
  58122. // Create lens flare post-process
  58123. this._createLensFlarePostProcess(scene, ratio);
  58124. // Create depth-of-field source post-process post lens-flare and disable it now
  58125. 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);
  58126. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  58127. }
  58128. if (this._hdrEnabled) {
  58129. // Create luminance
  58130. this._createLuminancePostProcesses(scene, this._floatTextureType);
  58131. // Create HDR
  58132. this._createHdrPostProcess(scene, ratio);
  58133. // Create depth-of-field source post-process post hdr and disable it now
  58134. 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);
  58135. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  58136. }
  58137. if (this._depthOfFieldEnabled) {
  58138. // Create gaussian blur used by depth-of-field
  58139. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  58140. // Create depth-of-field post-process
  58141. this._createDepthOfFieldPostProcess(scene, ratio);
  58142. }
  58143. if (this._motionBlurEnabled) {
  58144. // Create motion blur post-process
  58145. this._createMotionBlurPostProcess(scene, ratio);
  58146. }
  58147. if (this._cameras !== null) {
  58148. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58149. }
  58150. };
  58151. // Down Sample X4 Post-Processs
  58152. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  58153. var _this = this;
  58154. var downSampleX4Offsets = new Array(32);
  58155. 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);
  58156. this.downSampleX4PostProcess.onApply = function (effect) {
  58157. var id = 0;
  58158. var width = _this.downSampleX4PostProcess.width;
  58159. var height = _this.downSampleX4PostProcess.height;
  58160. for (var i = -2; i < 2; i++) {
  58161. for (var j = -2; j < 2; j++) {
  58162. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58163. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58164. id += 2;
  58165. }
  58166. }
  58167. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58168. };
  58169. // Add to pipeline
  58170. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58171. };
  58172. // Brightpass Post-Process
  58173. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58174. var _this = this;
  58175. var brightOffsets = new Array(8);
  58176. 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);
  58177. this.brightPassPostProcess.onApply = function (effect) {
  58178. var sU = (1.0 / _this.brightPassPostProcess.width);
  58179. var sV = (1.0 / _this.brightPassPostProcess.height);
  58180. brightOffsets[0] = -0.5 * sU;
  58181. brightOffsets[1] = 0.5 * sV;
  58182. brightOffsets[2] = 0.5 * sU;
  58183. brightOffsets[3] = 0.5 * sV;
  58184. brightOffsets[4] = -0.5 * sU;
  58185. brightOffsets[5] = -0.5 * sV;
  58186. brightOffsets[6] = 0.5 * sU;
  58187. brightOffsets[7] = -0.5 * sV;
  58188. effect.setArray2("dsOffsets", brightOffsets);
  58189. effect.setFloat("brightThreshold", _this.brightThreshold);
  58190. };
  58191. // Add to pipeline
  58192. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58193. };
  58194. // Create blur H&V post-processes
  58195. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58196. var _this = this;
  58197. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58198. var engine = scene.getEngine();
  58199. 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);
  58200. 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);
  58201. blurX.onActivateObservable.add(function () {
  58202. var dw = blurX.width / engine.getRenderWidth();
  58203. blurX.kernel = _this[blurWidthKey] * dw;
  58204. });
  58205. blurY.onActivateObservable.add(function () {
  58206. var dw = blurY.height / engine.getRenderHeight();
  58207. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  58208. });
  58209. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  58210. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  58211. this.blurHPostProcesses.push(blurX);
  58212. this.blurVPostProcesses.push(blurY);
  58213. };
  58214. // Create texture adder post-process
  58215. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58216. var _this = this;
  58217. 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);
  58218. this.textureAdderPostProcess.onApply = function (effect) {
  58219. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  58220. effect.setTexture("lensSampler", _this.lensTexture);
  58221. effect.setFloat("exposure", _this.exposure);
  58222. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  58223. };
  58224. // Add to pipeline
  58225. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58226. };
  58227. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  58228. var _this = this;
  58229. var geometryRenderer = scene.enableGeometryBufferRenderer();
  58230. geometryRenderer.enablePosition = true;
  58231. var geometry = geometryRenderer.getGBuffer();
  58232. // Base post-process
  58233. 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));
  58234. var depthValues = BABYLON.Vector2.Zero();
  58235. this.volumetricLightPostProcess.onApply = function (effect) {
  58236. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  58237. var generator = _this.sourceLight.getShadowGenerator();
  58238. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  58239. effect.setTexture("positionSampler", geometry.textures[2]);
  58240. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  58241. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  58242. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  58243. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  58244. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  58245. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  58246. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  58247. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  58248. effect.setVector2("depthValues", depthValues);
  58249. }
  58250. };
  58251. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  58252. // Smooth
  58253. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  58254. // Merge
  58255. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  58256. this.volumetricLightMergePostProces.onApply = function (effect) {
  58257. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  58258. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  58259. };
  58260. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  58261. };
  58262. // Create luminance
  58263. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  58264. var _this = this;
  58265. // Create luminance
  58266. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  58267. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  58268. var offsets = [];
  58269. this.luminancePostProcess.onApply = function (effect) {
  58270. var sU = (1.0 / _this.luminancePostProcess.width);
  58271. var sV = (1.0 / _this.luminancePostProcess.height);
  58272. offsets[0] = -0.5 * sU;
  58273. offsets[1] = 0.5 * sV;
  58274. offsets[2] = 0.5 * sU;
  58275. offsets[3] = 0.5 * sV;
  58276. offsets[4] = -0.5 * sU;
  58277. offsets[5] = -0.5 * sV;
  58278. offsets[6] = 0.5 * sU;
  58279. offsets[7] = -0.5 * sV;
  58280. effect.setArray2("lumOffsets", offsets);
  58281. };
  58282. // Add to pipeline
  58283. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  58284. // Create down sample luminance
  58285. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  58286. var size = Math.pow(3, i);
  58287. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  58288. if (i === 0) {
  58289. defines += "#define FINAL_DOWN_SAMPLER";
  58290. }
  58291. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  58292. this.luminanceDownSamplePostProcesses.push(postProcess);
  58293. }
  58294. // Create callbacks and add effects
  58295. var lastLuminance = this.luminancePostProcess;
  58296. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  58297. var downSampleOffsets = new Array(18);
  58298. pp.onApply = function (effect) {
  58299. if (!lastLuminance) {
  58300. return;
  58301. }
  58302. var id = 0;
  58303. for (var x = -1; x < 2; x++) {
  58304. for (var y = -1; y < 2; y++) {
  58305. downSampleOffsets[id] = x / lastLuminance.width;
  58306. downSampleOffsets[id + 1] = y / lastLuminance.height;
  58307. id += 2;
  58308. }
  58309. }
  58310. effect.setArray2("dsOffsets", downSampleOffsets);
  58311. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  58312. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58313. lastLuminance = _this.luminancePostProcess;
  58314. }
  58315. else {
  58316. lastLuminance = pp;
  58317. }
  58318. };
  58319. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58320. pp.onAfterRender = function (effect) {
  58321. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  58322. 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);
  58323. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  58324. };
  58325. }
  58326. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  58327. });
  58328. };
  58329. // Create HDR post-process
  58330. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  58331. var _this = this;
  58332. 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);
  58333. var outputLiminance = 1;
  58334. var time = 0;
  58335. var lastTime = 0;
  58336. this.hdrPostProcess.onApply = function (effect) {
  58337. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  58338. time += scene.getEngine().getDeltaTime();
  58339. if (outputLiminance < 0) {
  58340. outputLiminance = _this._hdrCurrentLuminance;
  58341. }
  58342. else {
  58343. var dt = (lastTime - time) / 1000.0;
  58344. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  58345. outputLiminance += _this.hdrDecreaseRate * dt;
  58346. }
  58347. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  58348. outputLiminance -= _this.hdrIncreaseRate * dt;
  58349. }
  58350. else {
  58351. outputLiminance = _this._hdrCurrentLuminance;
  58352. }
  58353. }
  58354. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  58355. effect.setFloat("averageLuminance", outputLiminance);
  58356. lastTime = time;
  58357. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  58358. };
  58359. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  58360. };
  58361. // Create lens flare post-process
  58362. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  58363. var _this = this;
  58364. 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);
  58365. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  58366. this._createBlurPostProcesses(scene, ratio / 4, 2);
  58367. 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);
  58368. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  58369. var resolution = new BABYLON.Vector2(0, 0);
  58370. // Lens flare
  58371. this.lensFlarePostProcess.onApply = function (effect) {
  58372. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  58373. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  58374. effect.setFloat("strength", _this.lensFlareStrength);
  58375. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  58376. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  58377. // Shift
  58378. resolution.x = _this.lensFlarePostProcess.width;
  58379. resolution.y = _this.lensFlarePostProcess.height;
  58380. effect.setVector2("resolution", resolution);
  58381. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  58382. };
  58383. // Compose
  58384. 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);
  58385. 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);
  58386. this.lensFlareComposePostProcess.onApply = function (effect) {
  58387. if (!_this._scene.activeCamera) {
  58388. return;
  58389. }
  58390. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58391. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  58392. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  58393. // Lens start rotation matrix
  58394. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  58395. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  58396. 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));
  58397. camRot *= 4.0;
  58398. 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);
  58399. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  58400. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  58401. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  58402. };
  58403. };
  58404. // Create depth-of-field post-process
  58405. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  58406. var _this = this;
  58407. 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);
  58408. this.depthOfFieldPostProcess.onApply = function (effect) {
  58409. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58410. effect.setTexture("depthSampler", _this._getDepthTexture());
  58411. effect.setFloat("distance", _this.depthOfFieldDistance);
  58412. };
  58413. // Add to pipeline
  58414. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  58415. };
  58416. // Create motion blur post-process
  58417. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  58418. var _this = this;
  58419. 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);
  58420. var motionScale = 0;
  58421. var prevViewProjection = BABYLON.Matrix.Identity();
  58422. var invViewProjection = BABYLON.Matrix.Identity();
  58423. var viewProjection = BABYLON.Matrix.Identity();
  58424. var screenSize = BABYLON.Vector2.Zero();
  58425. this.motionBlurPostProcess.onApply = function (effect) {
  58426. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  58427. viewProjection.invertToRef(invViewProjection);
  58428. effect.setMatrix("inverseViewProjection", invViewProjection);
  58429. effect.setMatrix("prevViewProjection", prevViewProjection);
  58430. prevViewProjection = viewProjection;
  58431. screenSize.x = _this.motionBlurPostProcess.width;
  58432. screenSize.y = _this.motionBlurPostProcess.height;
  58433. effect.setVector2("screenSize", screenSize);
  58434. motionScale = scene.getEngine().getFps() / 60.0;
  58435. effect.setFloat("motionScale", motionScale);
  58436. effect.setFloat("motionStrength", _this.motionStrength);
  58437. effect.setTexture("depthSampler", _this._getDepthTexture());
  58438. };
  58439. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  58440. };
  58441. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  58442. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  58443. var renderer = this._scene.enableGeometryBufferRenderer();
  58444. return renderer.getGBuffer().textures[0];
  58445. }
  58446. return this._scene.enableDepthRenderer().getDepthMap();
  58447. };
  58448. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  58449. for (var i = 0; i < this._cameras.length; i++) {
  58450. var camera = this._cameras[i];
  58451. if (this.originalPostProcess) {
  58452. this.originalPostProcess.dispose(camera);
  58453. }
  58454. if (this.downSampleX4PostProcess) {
  58455. this.downSampleX4PostProcess.dispose(camera);
  58456. }
  58457. if (this.brightPassPostProcess) {
  58458. this.brightPassPostProcess.dispose(camera);
  58459. }
  58460. if (this.textureAdderPostProcess) {
  58461. this.textureAdderPostProcess.dispose(camera);
  58462. }
  58463. if (this.textureAdderFinalPostProcess) {
  58464. this.textureAdderFinalPostProcess.dispose(camera);
  58465. }
  58466. if (this.volumetricLightPostProcess) {
  58467. this.volumetricLightPostProcess.dispose(camera);
  58468. }
  58469. if (this.volumetricLightSmoothXPostProcess) {
  58470. this.volumetricLightSmoothXPostProcess.dispose(camera);
  58471. }
  58472. if (this.volumetricLightSmoothYPostProcess) {
  58473. this.volumetricLightSmoothYPostProcess.dispose(camera);
  58474. }
  58475. if (this.volumetricLightMergePostProces) {
  58476. this.volumetricLightMergePostProces.dispose(camera);
  58477. }
  58478. if (this.volumetricLightFinalPostProcess) {
  58479. this.volumetricLightFinalPostProcess.dispose(camera);
  58480. }
  58481. if (this.lensFlarePostProcess) {
  58482. this.lensFlarePostProcess.dispose(camera);
  58483. }
  58484. if (this.lensFlareComposePostProcess) {
  58485. this.lensFlareComposePostProcess.dispose(camera);
  58486. }
  58487. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  58488. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  58489. }
  58490. if (this.luminancePostProcess) {
  58491. this.luminancePostProcess.dispose(camera);
  58492. }
  58493. if (this.hdrPostProcess) {
  58494. this.hdrPostProcess.dispose(camera);
  58495. }
  58496. if (this.hdrFinalPostProcess) {
  58497. this.hdrFinalPostProcess.dispose(camera);
  58498. }
  58499. if (this.depthOfFieldPostProcess) {
  58500. this.depthOfFieldPostProcess.dispose(camera);
  58501. }
  58502. if (this.motionBlurPostProcess) {
  58503. this.motionBlurPostProcess.dispose(camera);
  58504. }
  58505. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  58506. this.blurHPostProcesses[j].dispose(camera);
  58507. }
  58508. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  58509. this.blurVPostProcesses[j].dispose(camera);
  58510. }
  58511. }
  58512. this.originalPostProcess = null;
  58513. this.downSampleX4PostProcess = null;
  58514. this.brightPassPostProcess = null;
  58515. this.textureAdderPostProcess = null;
  58516. this.textureAdderFinalPostProcess = null;
  58517. this.volumetricLightPostProcess = null;
  58518. this.volumetricLightSmoothXPostProcess = null;
  58519. this.volumetricLightSmoothYPostProcess = null;
  58520. this.volumetricLightMergePostProces = null;
  58521. this.volumetricLightFinalPostProcess = null;
  58522. this.lensFlarePostProcess = null;
  58523. this.lensFlareComposePostProcess = null;
  58524. this.luminancePostProcess = null;
  58525. this.hdrPostProcess = null;
  58526. this.hdrFinalPostProcess = null;
  58527. this.depthOfFieldPostProcess = null;
  58528. this.motionBlurPostProcess = null;
  58529. this.luminanceDownSamplePostProcesses = [];
  58530. this.blurHPostProcesses = [];
  58531. this.blurVPostProcesses = [];
  58532. };
  58533. // Dispose
  58534. StandardRenderingPipeline.prototype.dispose = function () {
  58535. this._disposePostProcesses();
  58536. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58537. _super.prototype.dispose.call(this);
  58538. };
  58539. // Serialize rendering pipeline
  58540. StandardRenderingPipeline.prototype.serialize = function () {
  58541. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58542. serializationObject.customType = "StandardRenderingPipeline";
  58543. return serializationObject;
  58544. };
  58545. /**
  58546. * Static members
  58547. */
  58548. // Parse serialized pipeline
  58549. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58550. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  58551. };
  58552. // Luminance steps
  58553. StandardRenderingPipeline.LuminanceSteps = 6;
  58554. __decorate([
  58555. BABYLON.serialize()
  58556. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  58557. __decorate([
  58558. BABYLON.serialize()
  58559. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  58560. __decorate([
  58561. BABYLON.serialize()
  58562. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  58563. __decorate([
  58564. BABYLON.serialize()
  58565. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  58566. __decorate([
  58567. BABYLON.serializeAsTexture("lensTexture")
  58568. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  58569. __decorate([
  58570. BABYLON.serialize()
  58571. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  58572. __decorate([
  58573. BABYLON.serialize()
  58574. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  58575. __decorate([
  58576. BABYLON.serialize()
  58577. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  58578. __decorate([
  58579. BABYLON.serialize()
  58580. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  58581. __decorate([
  58582. BABYLON.serialize()
  58583. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  58584. __decorate([
  58585. BABYLON.serialize()
  58586. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  58587. __decorate([
  58588. BABYLON.serializeAsTexture("lensColorTexture")
  58589. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  58590. __decorate([
  58591. BABYLON.serialize()
  58592. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  58593. __decorate([
  58594. BABYLON.serialize()
  58595. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  58596. __decorate([
  58597. BABYLON.serialize()
  58598. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  58599. __decorate([
  58600. BABYLON.serialize()
  58601. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  58602. __decorate([
  58603. BABYLON.serializeAsTexture("lensStarTexture")
  58604. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  58605. __decorate([
  58606. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  58607. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  58608. __decorate([
  58609. BABYLON.serialize()
  58610. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  58611. __decorate([
  58612. BABYLON.serialize()
  58613. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  58614. __decorate([
  58615. BABYLON.serialize()
  58616. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  58617. __decorate([
  58618. BABYLON.serialize()
  58619. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  58620. __decorate([
  58621. BABYLON.serialize()
  58622. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  58623. __decorate([
  58624. BABYLON.serialize()
  58625. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  58626. __decorate([
  58627. BABYLON.serialize()
  58628. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  58629. __decorate([
  58630. BABYLON.serialize()
  58631. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  58632. __decorate([
  58633. BABYLON.serialize()
  58634. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  58635. __decorate([
  58636. BABYLON.serialize()
  58637. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  58638. __decorate([
  58639. BABYLON.serialize()
  58640. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  58641. return StandardRenderingPipeline;
  58642. }(BABYLON.PostProcessRenderPipeline));
  58643. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  58644. })(BABYLON || (BABYLON = {}));
  58645. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  58646. var BABYLON;
  58647. (function (BABYLON) {
  58648. var FxaaPostProcess = /** @class */ (function (_super) {
  58649. __extends(FxaaPostProcess, _super);
  58650. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58651. if (camera === void 0) { camera = null; }
  58652. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58653. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  58654. _this.onApplyObservable.add(function (effect) {
  58655. var texelSize = _this.texelSize;
  58656. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  58657. });
  58658. return _this;
  58659. }
  58660. return FxaaPostProcess;
  58661. }(BABYLON.PostProcess));
  58662. BABYLON.FxaaPostProcess = FxaaPostProcess;
  58663. })(BABYLON || (BABYLON = {}));
  58664. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  58665. var BABYLON;
  58666. (function (BABYLON) {
  58667. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  58668. __extends(DefaultRenderingPipeline, _super);
  58669. /**
  58670. * @constructor
  58671. * @param {string} name - The rendering pipeline name
  58672. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58673. * @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)
  58674. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58675. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  58676. */
  58677. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  58678. if (automaticBuild === void 0) { automaticBuild = true; }
  58679. var _this = _super.call(this, scene.getEngine(), name) || this;
  58680. _this.PassPostProcessId = "PassPostProcessEffect";
  58681. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  58682. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  58683. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  58684. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  58685. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  58686. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  58687. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  58688. // IAnimatable
  58689. _this.animations = [];
  58690. // Values
  58691. _this._bloomEnabled = false;
  58692. _this._fxaaEnabled = false;
  58693. _this._imageProcessingEnabled = true;
  58694. _this._bloomScale = 0.6;
  58695. _this._buildAllowed = true;
  58696. /**
  58697. * Specifies the size of the bloom blur kernel, relative to the final output size
  58698. */
  58699. _this.bloomKernel = 64;
  58700. /**
  58701. * Specifies the weight of the bloom in the final rendering
  58702. */
  58703. _this._bloomWeight = 0.15;
  58704. _this._cameras = cameras || [];
  58705. _this._buildAllowed = automaticBuild;
  58706. // Initialize
  58707. _this._scene = scene;
  58708. var caps = _this._scene.getEngine().getCaps();
  58709. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  58710. // Misc
  58711. if (_this._hdr) {
  58712. if (caps.textureHalfFloatRender) {
  58713. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58714. }
  58715. else if (caps.textureFloatRender) {
  58716. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58717. }
  58718. }
  58719. else {
  58720. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58721. }
  58722. // Attach
  58723. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58724. _this._buildPipeline();
  58725. return _this;
  58726. }
  58727. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  58728. get: function () {
  58729. return this._bloomWeight;
  58730. },
  58731. set: function (value) {
  58732. if (this._bloomWeight === value) {
  58733. return;
  58734. }
  58735. this._bloomWeight = value;
  58736. if (this._hdr && this.copyBack) {
  58737. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  58738. }
  58739. },
  58740. enumerable: true,
  58741. configurable: true
  58742. });
  58743. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  58744. get: function () {
  58745. return this._bloomScale;
  58746. },
  58747. set: function (value) {
  58748. if (this._bloomScale === value) {
  58749. return;
  58750. }
  58751. this._bloomScale = value;
  58752. this._buildPipeline();
  58753. },
  58754. enumerable: true,
  58755. configurable: true
  58756. });
  58757. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  58758. get: function () {
  58759. return this._bloomEnabled;
  58760. },
  58761. set: function (enabled) {
  58762. if (this._bloomEnabled === enabled) {
  58763. return;
  58764. }
  58765. this._bloomEnabled = enabled;
  58766. this._buildPipeline();
  58767. },
  58768. enumerable: true,
  58769. configurable: true
  58770. });
  58771. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  58772. get: function () {
  58773. return this._fxaaEnabled;
  58774. },
  58775. set: function (enabled) {
  58776. if (this._fxaaEnabled === enabled) {
  58777. return;
  58778. }
  58779. this._fxaaEnabled = enabled;
  58780. this._buildPipeline();
  58781. },
  58782. enumerable: true,
  58783. configurable: true
  58784. });
  58785. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  58786. get: function () {
  58787. return this._imageProcessingEnabled;
  58788. },
  58789. set: function (enabled) {
  58790. if (this._imageProcessingEnabled === enabled) {
  58791. return;
  58792. }
  58793. this._imageProcessingEnabled = enabled;
  58794. this._buildPipeline();
  58795. },
  58796. enumerable: true,
  58797. configurable: true
  58798. });
  58799. /**
  58800. * Force the compilation of the entire pipeline.
  58801. */
  58802. DefaultRenderingPipeline.prototype.prepare = function () {
  58803. var previousState = this._buildAllowed;
  58804. this._buildAllowed = true;
  58805. this._buildPipeline();
  58806. this._buildAllowed = previousState;
  58807. };
  58808. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  58809. var _this = this;
  58810. if (!this._buildAllowed) {
  58811. return;
  58812. }
  58813. var engine = this._scene.getEngine();
  58814. this._disposePostProcesses();
  58815. this._reset();
  58816. if (this.bloomEnabled) {
  58817. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58818. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  58819. if (!this._hdr) {
  58820. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58821. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  58822. this.highlights.autoClear = false;
  58823. this.highlights.alwaysForcePOT = true;
  58824. }
  58825. 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);
  58826. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  58827. this.blurX.alwaysForcePOT = true;
  58828. this.blurX.autoClear = false;
  58829. this.blurX.onActivateObservable.add(function () {
  58830. var dw = _this.blurX.width / engine.getRenderWidth(true);
  58831. _this.blurX.kernel = _this.bloomKernel * dw;
  58832. });
  58833. 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);
  58834. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  58835. this.blurY.alwaysForcePOT = true;
  58836. this.blurY.autoClear = false;
  58837. this.blurY.onActivateObservable.add(function () {
  58838. var dh = _this.blurY.height / engine.getRenderHeight(true);
  58839. _this.blurY.kernel = _this.bloomKernel * dh;
  58840. });
  58841. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58842. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  58843. this.copyBack.alwaysForcePOT = true;
  58844. if (this._hdr) {
  58845. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  58846. var w = this.bloomWeight;
  58847. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  58848. }
  58849. else {
  58850. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  58851. }
  58852. this.copyBack.autoClear = false;
  58853. }
  58854. if (this._imageProcessingEnabled) {
  58855. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58856. if (this._hdr) {
  58857. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  58858. }
  58859. else {
  58860. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  58861. }
  58862. }
  58863. if (this.fxaaEnabled) {
  58864. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58865. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  58866. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58867. }
  58868. else {
  58869. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58870. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  58871. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58872. }
  58873. if (this.bloomEnabled) {
  58874. if (this._hdr) {
  58875. this.copyBack.shareOutputWith(this.blurX);
  58876. if (this.imageProcessing) {
  58877. this.imageProcessing.shareOutputWith(this.pass);
  58878. this.imageProcessing.autoClear = false;
  58879. }
  58880. else if (this.fxaa) {
  58881. this.fxaa.shareOutputWith(this.pass);
  58882. }
  58883. else {
  58884. this.finalMerge.shareOutputWith(this.pass);
  58885. }
  58886. }
  58887. else {
  58888. if (this.fxaa) {
  58889. this.fxaa.shareOutputWith(this.pass);
  58890. }
  58891. else {
  58892. this.finalMerge.shareOutputWith(this.pass);
  58893. }
  58894. }
  58895. }
  58896. if (this._cameras !== null) {
  58897. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58898. }
  58899. };
  58900. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  58901. for (var i = 0; i < this._cameras.length; i++) {
  58902. var camera = this._cameras[i];
  58903. if (this.pass) {
  58904. this.pass.dispose(camera);
  58905. }
  58906. if (this.highlights) {
  58907. this.highlights.dispose(camera);
  58908. }
  58909. if (this.blurX) {
  58910. this.blurX.dispose(camera);
  58911. }
  58912. if (this.blurY) {
  58913. this.blurY.dispose(camera);
  58914. }
  58915. if (this.copyBack) {
  58916. this.copyBack.dispose(camera);
  58917. }
  58918. if (this.imageProcessing) {
  58919. this.imageProcessing.dispose(camera);
  58920. }
  58921. if (this.fxaa) {
  58922. this.fxaa.dispose(camera);
  58923. }
  58924. if (this.finalMerge) {
  58925. this.finalMerge.dispose(camera);
  58926. }
  58927. }
  58928. this.pass = null;
  58929. this.highlights = null;
  58930. this.blurX = null;
  58931. this.blurY = null;
  58932. this.copyBack = null;
  58933. this.imageProcessing = null;
  58934. this.fxaa = null;
  58935. this.finalMerge = null;
  58936. };
  58937. // Dispose
  58938. DefaultRenderingPipeline.prototype.dispose = function () {
  58939. this._disposePostProcesses();
  58940. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58941. _super.prototype.dispose.call(this);
  58942. };
  58943. // Serialize rendering pipeline
  58944. DefaultRenderingPipeline.prototype.serialize = function () {
  58945. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58946. serializationObject.customType = "DefaultRenderingPipeline";
  58947. return serializationObject;
  58948. };
  58949. // Parse serialized pipeline
  58950. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58951. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  58952. };
  58953. __decorate([
  58954. BABYLON.serialize()
  58955. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  58956. __decorate([
  58957. BABYLON.serialize()
  58958. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  58959. __decorate([
  58960. BABYLON.serialize()
  58961. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  58962. __decorate([
  58963. BABYLON.serialize()
  58964. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  58965. __decorate([
  58966. BABYLON.serialize()
  58967. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  58968. __decorate([
  58969. BABYLON.serialize()
  58970. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  58971. __decorate([
  58972. BABYLON.serialize()
  58973. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  58974. __decorate([
  58975. BABYLON.serialize()
  58976. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  58977. return DefaultRenderingPipeline;
  58978. }(BABYLON.PostProcessRenderPipeline));
  58979. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  58980. })(BABYLON || (BABYLON = {}));
  58981. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  58982. var BABYLON;
  58983. (function (BABYLON) {
  58984. var GeometryBufferRenderer = /** @class */ (function () {
  58985. function GeometryBufferRenderer(scene, ratio) {
  58986. if (ratio === void 0) { ratio = 1; }
  58987. this._enablePosition = false;
  58988. this._scene = scene;
  58989. this._ratio = ratio;
  58990. // Render target
  58991. this._createRenderTargets();
  58992. }
  58993. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  58994. set: function (meshes) {
  58995. this._multiRenderTarget.renderList = meshes;
  58996. },
  58997. enumerable: true,
  58998. configurable: true
  58999. });
  59000. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  59001. get: function () {
  59002. return this._multiRenderTarget.isSupported;
  59003. },
  59004. enumerable: true,
  59005. configurable: true
  59006. });
  59007. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  59008. get: function () {
  59009. return this._enablePosition;
  59010. },
  59011. set: function (enable) {
  59012. this._enablePosition = enable;
  59013. this.dispose();
  59014. this._createRenderTargets();
  59015. },
  59016. enumerable: true,
  59017. configurable: true
  59018. });
  59019. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  59020. var material = subMesh.getMaterial();
  59021. if (material && material.disableDepthWrite) {
  59022. return false;
  59023. }
  59024. var defines = [];
  59025. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  59026. var mesh = subMesh.getMesh();
  59027. // Alpha test
  59028. if (material && material.needAlphaTesting()) {
  59029. defines.push("#define ALPHATEST");
  59030. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59031. attribs.push(BABYLON.VertexBuffer.UVKind);
  59032. defines.push("#define UV1");
  59033. }
  59034. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59035. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59036. defines.push("#define UV2");
  59037. }
  59038. }
  59039. // Buffers
  59040. if (this._enablePosition) {
  59041. defines.push("#define POSITION");
  59042. }
  59043. // Bones
  59044. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59045. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59046. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59047. if (mesh.numBoneInfluencers > 4) {
  59048. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59049. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59050. }
  59051. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59052. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59053. }
  59054. else {
  59055. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59056. }
  59057. // Instances
  59058. if (useInstances) {
  59059. defines.push("#define INSTANCES");
  59060. attribs.push("world0");
  59061. attribs.push("world1");
  59062. attribs.push("world2");
  59063. attribs.push("world3");
  59064. }
  59065. // Get correct effect
  59066. var join = defines.join("\n");
  59067. if (this._cachedDefines !== join) {
  59068. this._cachedDefines = join;
  59069. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  59070. }
  59071. return this._effect.isReady();
  59072. };
  59073. GeometryBufferRenderer.prototype.getGBuffer = function () {
  59074. return this._multiRenderTarget;
  59075. };
  59076. // Methods
  59077. GeometryBufferRenderer.prototype.dispose = function () {
  59078. this.getGBuffer().dispose();
  59079. };
  59080. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  59081. var _this = this;
  59082. var engine = this._scene.getEngine();
  59083. var count = this._enablePosition ? 3 : 2;
  59084. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  59085. if (!this.isSupported) {
  59086. return;
  59087. }
  59088. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59089. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59090. this._multiRenderTarget.refreshRate = 1;
  59091. this._multiRenderTarget.renderParticles = false;
  59092. this._multiRenderTarget.renderList = null;
  59093. // set default depth value to 1.0 (far away)
  59094. this._multiRenderTarget.onClearObservable.add(function (engine) {
  59095. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  59096. });
  59097. // Custom render function
  59098. var renderSubMesh = function (subMesh) {
  59099. var mesh = subMesh.getRenderingMesh();
  59100. var scene = _this._scene;
  59101. var engine = scene.getEngine();
  59102. var material = subMesh.getMaterial();
  59103. if (!material) {
  59104. return;
  59105. }
  59106. // Culling
  59107. engine.setState(material.backFaceCulling);
  59108. // Managing instances
  59109. var batch = mesh._getInstancesRenderList(subMesh._id);
  59110. if (batch.mustReturn) {
  59111. return;
  59112. }
  59113. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59114. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59115. engine.enableEffect(_this._effect);
  59116. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59117. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59118. _this._effect.setMatrix("view", scene.getViewMatrix());
  59119. // Alpha test
  59120. if (material && material.needAlphaTesting()) {
  59121. var alphaTexture = material.getAlphaTestTexture();
  59122. if (alphaTexture) {
  59123. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59124. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59125. }
  59126. }
  59127. // Bones
  59128. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59129. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59130. }
  59131. // Draw
  59132. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59133. }
  59134. };
  59135. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59136. var index;
  59137. if (depthOnlySubMeshes.length) {
  59138. engine.setColorWrite(false);
  59139. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59140. renderSubMesh(depthOnlySubMeshes.data[index]);
  59141. }
  59142. engine.setColorWrite(true);
  59143. }
  59144. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59145. renderSubMesh(opaqueSubMeshes.data[index]);
  59146. }
  59147. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59148. renderSubMesh(alphaTestSubMeshes.data[index]);
  59149. }
  59150. };
  59151. };
  59152. return GeometryBufferRenderer;
  59153. }());
  59154. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  59155. })(BABYLON || (BABYLON = {}));
  59156. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  59157. var BABYLON;
  59158. (function (BABYLON) {
  59159. var RefractionPostProcess = /** @class */ (function (_super) {
  59160. __extends(RefractionPostProcess, _super);
  59161. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  59162. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59163. _this.color = color;
  59164. _this.depth = depth;
  59165. _this.colorLevel = colorLevel;
  59166. _this.onActivateObservable.add(function (cam) {
  59167. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59168. });
  59169. _this.onApplyObservable.add(function (effect) {
  59170. effect.setColor3("baseColor", _this.color);
  59171. effect.setFloat("depth", _this.depth);
  59172. effect.setFloat("colorLevel", _this.colorLevel);
  59173. effect.setTexture("refractionSampler", _this._refRexture);
  59174. });
  59175. return _this;
  59176. }
  59177. // Methods
  59178. RefractionPostProcess.prototype.dispose = function (camera) {
  59179. if (this._refRexture) {
  59180. this._refRexture.dispose();
  59181. }
  59182. _super.prototype.dispose.call(this, camera);
  59183. };
  59184. return RefractionPostProcess;
  59185. }(BABYLON.PostProcess));
  59186. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59187. })(BABYLON || (BABYLON = {}));
  59188. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59189. var BABYLON;
  59190. (function (BABYLON) {
  59191. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59192. __extends(BlackAndWhitePostProcess, _super);
  59193. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  59194. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  59195. _this.degree = 1;
  59196. _this.onApplyObservable.add(function (effect) {
  59197. effect.setFloat("degree", _this.degree);
  59198. });
  59199. return _this;
  59200. }
  59201. return BlackAndWhitePostProcess;
  59202. }(BABYLON.PostProcess));
  59203. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  59204. })(BABYLON || (BABYLON = {}));
  59205. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  59206. var BABYLON;
  59207. (function (BABYLON) {
  59208. var ConvolutionPostProcess = /** @class */ (function (_super) {
  59209. __extends(ConvolutionPostProcess, _super);
  59210. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  59211. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  59212. _this.kernel = kernel;
  59213. _this.onApply = function (effect) {
  59214. effect.setFloat2("screenSize", _this.width, _this.height);
  59215. effect.setArray("kernel", _this.kernel);
  59216. };
  59217. return _this;
  59218. }
  59219. // Statics
  59220. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  59221. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  59222. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  59223. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  59224. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  59225. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  59226. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  59227. return ConvolutionPostProcess;
  59228. }(BABYLON.PostProcess));
  59229. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  59230. })(BABYLON || (BABYLON = {}));
  59231. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  59232. var BABYLON;
  59233. (function (BABYLON) {
  59234. var FilterPostProcess = /** @class */ (function (_super) {
  59235. __extends(FilterPostProcess, _super);
  59236. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  59237. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  59238. _this.kernelMatrix = kernelMatrix;
  59239. _this.onApply = function (effect) {
  59240. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  59241. };
  59242. return _this;
  59243. }
  59244. return FilterPostProcess;
  59245. }(BABYLON.PostProcess));
  59246. BABYLON.FilterPostProcess = FilterPostProcess;
  59247. })(BABYLON || (BABYLON = {}));
  59248. //# sourceMappingURL=babylon.filterPostProcess.js.map
  59249. var BABYLON;
  59250. (function (BABYLON) {
  59251. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  59252. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  59253. __extends(VolumetricLightScatteringPostProcess, _super);
  59254. /**
  59255. * @constructor
  59256. * @param {string} name - The post-process name
  59257. * @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)
  59258. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  59259. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  59260. * @param {number} samples - The post-process quality, default 100
  59261. * @param {number} samplingMode - The post-process filtering mode
  59262. * @param {BABYLON.Engine} engine - The babylon engine
  59263. * @param {boolean} reusable - If the post-process is reusable
  59264. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  59265. */
  59266. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  59267. if (samples === void 0) { samples = 100; }
  59268. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59269. 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;
  59270. _this._screenCoordinates = BABYLON.Vector2.Zero();
  59271. /**
  59272. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  59273. * @type {Vector3}
  59274. */
  59275. _this.customMeshPosition = BABYLON.Vector3.Zero();
  59276. /**
  59277. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  59278. * @type {boolean}
  59279. */
  59280. _this.useCustomMeshPosition = false;
  59281. /**
  59282. * If the post-process should inverse the light scattering direction
  59283. * @type {boolean}
  59284. */
  59285. _this.invert = true;
  59286. /**
  59287. * Array containing the excluded meshes not rendered in the internal pass
  59288. */
  59289. _this.excludedMeshes = new Array();
  59290. /**
  59291. * Controls the overall intensity of the post-process
  59292. * @type {number}
  59293. */
  59294. _this.exposure = 0.3;
  59295. /**
  59296. * Dissipates each sample's contribution in range [0, 1]
  59297. * @type {number}
  59298. */
  59299. _this.decay = 0.96815;
  59300. /**
  59301. * Controls the overall intensity of each sample
  59302. * @type {number}
  59303. */
  59304. _this.weight = 0.58767;
  59305. /**
  59306. * Controls the density of each sample
  59307. * @type {number}
  59308. */
  59309. _this.density = 0.926;
  59310. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  59311. engine = scene.getEngine();
  59312. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  59313. // Configure mesh
  59314. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  59315. // Configure
  59316. _this._createPass(scene, ratio.passRatio || ratio);
  59317. _this.onActivate = function (camera) {
  59318. if (!_this.isSupported) {
  59319. _this.dispose(camera);
  59320. }
  59321. _this.onActivate = null;
  59322. };
  59323. _this.onApplyObservable.add(function (effect) {
  59324. _this._updateMeshScreenCoordinates(scene);
  59325. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  59326. effect.setFloat("exposure", _this.exposure);
  59327. effect.setFloat("decay", _this.decay);
  59328. effect.setFloat("weight", _this.weight);
  59329. effect.setFloat("density", _this.density);
  59330. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  59331. });
  59332. return _this;
  59333. }
  59334. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  59335. get: function () {
  59336. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59337. return false;
  59338. },
  59339. set: function (useDiffuseColor) {
  59340. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59341. },
  59342. enumerable: true,
  59343. configurable: true
  59344. });
  59345. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  59346. return "VolumetricLightScatteringPostProcess";
  59347. };
  59348. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  59349. var mesh = subMesh.getMesh();
  59350. // Render this.mesh as default
  59351. if (mesh === this.mesh && mesh.material) {
  59352. return mesh.material.isReady(mesh);
  59353. }
  59354. var defines = [];
  59355. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59356. var material = subMesh.getMaterial();
  59357. // Alpha test
  59358. if (material) {
  59359. if (material.needAlphaTesting()) {
  59360. defines.push("#define ALPHATEST");
  59361. }
  59362. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59363. attribs.push(BABYLON.VertexBuffer.UVKind);
  59364. defines.push("#define UV1");
  59365. }
  59366. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59367. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59368. defines.push("#define UV2");
  59369. }
  59370. }
  59371. // Bones
  59372. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59373. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59374. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59375. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59376. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  59377. }
  59378. else {
  59379. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59380. }
  59381. // Instances
  59382. if (useInstances) {
  59383. defines.push("#define INSTANCES");
  59384. attribs.push("world0");
  59385. attribs.push("world1");
  59386. attribs.push("world2");
  59387. attribs.push("world3");
  59388. }
  59389. // Get correct effect
  59390. var join = defines.join("\n");
  59391. if (this._cachedDefines !== join) {
  59392. this._cachedDefines = join;
  59393. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  59394. }
  59395. return this._volumetricLightScatteringPass.isReady();
  59396. };
  59397. /**
  59398. * Sets the new light position for light scattering effect
  59399. * @param {BABYLON.Vector3} The new custom light position
  59400. */
  59401. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  59402. this.customMeshPosition = position;
  59403. };
  59404. /**
  59405. * Returns the light position for light scattering effect
  59406. * @return {BABYLON.Vector3} The custom light position
  59407. */
  59408. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  59409. return this.customMeshPosition;
  59410. };
  59411. /**
  59412. * Disposes the internal assets and detaches the post-process from the camera
  59413. */
  59414. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  59415. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  59416. if (rttIndex !== -1) {
  59417. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  59418. }
  59419. this._volumetricLightScatteringRTT.dispose();
  59420. _super.prototype.dispose.call(this, camera);
  59421. };
  59422. /**
  59423. * Returns the render target texture used by the post-process
  59424. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  59425. */
  59426. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  59427. return this._volumetricLightScatteringRTT;
  59428. };
  59429. // Private methods
  59430. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  59431. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  59432. return true;
  59433. }
  59434. return false;
  59435. };
  59436. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  59437. var _this = this;
  59438. var engine = scene.getEngine();
  59439. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59440. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59441. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59442. this._volumetricLightScatteringRTT.renderList = null;
  59443. this._volumetricLightScatteringRTT.renderParticles = false;
  59444. var camera = this.getCamera();
  59445. if (camera) {
  59446. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59447. }
  59448. else {
  59449. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59450. }
  59451. // Custom render function for submeshes
  59452. var renderSubMesh = function (subMesh) {
  59453. var mesh = subMesh.getRenderingMesh();
  59454. if (_this._meshExcluded(mesh)) {
  59455. return;
  59456. }
  59457. var material = subMesh.getMaterial();
  59458. if (!material) {
  59459. return;
  59460. }
  59461. var scene = mesh.getScene();
  59462. var engine = scene.getEngine();
  59463. // Culling
  59464. engine.setState(material.backFaceCulling);
  59465. // Managing instances
  59466. var batch = mesh._getInstancesRenderList(subMesh._id);
  59467. if (batch.mustReturn) {
  59468. return;
  59469. }
  59470. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59471. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59472. var effect = _this._volumetricLightScatteringPass;
  59473. if (mesh === _this.mesh) {
  59474. if (subMesh.effect) {
  59475. effect = subMesh.effect;
  59476. }
  59477. else {
  59478. effect = material.getEffect();
  59479. }
  59480. }
  59481. engine.enableEffect(effect);
  59482. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  59483. if (mesh === _this.mesh) {
  59484. material.bind(mesh.getWorldMatrix(), mesh);
  59485. }
  59486. else {
  59487. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  59488. // Alpha test
  59489. if (material && material.needAlphaTesting()) {
  59490. var alphaTexture = material.getAlphaTestTexture();
  59491. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  59492. if (alphaTexture) {
  59493. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59494. }
  59495. }
  59496. // Bones
  59497. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59498. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59499. }
  59500. }
  59501. // Draw
  59502. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  59503. }
  59504. };
  59505. // Render target texture callbacks
  59506. var savedSceneClearColor;
  59507. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  59508. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  59509. savedSceneClearColor = scene.clearColor;
  59510. scene.clearColor = sceneClearColor;
  59511. });
  59512. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  59513. scene.clearColor = savedSceneClearColor;
  59514. });
  59515. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59516. var engine = scene.getEngine();
  59517. var index;
  59518. if (depthOnlySubMeshes.length) {
  59519. engine.setColorWrite(false);
  59520. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59521. renderSubMesh(depthOnlySubMeshes.data[index]);
  59522. }
  59523. engine.setColorWrite(true);
  59524. }
  59525. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59526. renderSubMesh(opaqueSubMeshes.data[index]);
  59527. }
  59528. engine.setAlphaTesting(true);
  59529. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59530. renderSubMesh(alphaTestSubMeshes.data[index]);
  59531. }
  59532. engine.setAlphaTesting(false);
  59533. if (transparentSubMeshes.length) {
  59534. // Sort sub meshes
  59535. for (index = 0; index < transparentSubMeshes.length; index++) {
  59536. var submesh = transparentSubMeshes.data[index];
  59537. var boundingInfo = submesh.getBoundingInfo();
  59538. if (boundingInfo && scene.activeCamera) {
  59539. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  59540. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  59541. }
  59542. }
  59543. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  59544. sortedArray.sort(function (a, b) {
  59545. // Alpha index first
  59546. if (a._alphaIndex > b._alphaIndex) {
  59547. return 1;
  59548. }
  59549. if (a._alphaIndex < b._alphaIndex) {
  59550. return -1;
  59551. }
  59552. // Then distance to camera
  59553. if (a._distanceToCamera < b._distanceToCamera) {
  59554. return 1;
  59555. }
  59556. if (a._distanceToCamera > b._distanceToCamera) {
  59557. return -1;
  59558. }
  59559. return 0;
  59560. });
  59561. // Render sub meshes
  59562. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59563. for (index = 0; index < sortedArray.length; index++) {
  59564. renderSubMesh(sortedArray[index]);
  59565. }
  59566. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59567. }
  59568. };
  59569. };
  59570. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  59571. var transform = scene.getTransformMatrix();
  59572. var meshPosition;
  59573. if (this.useCustomMeshPosition) {
  59574. meshPosition = this.customMeshPosition;
  59575. }
  59576. else if (this.attachedNode) {
  59577. meshPosition = this.attachedNode.position;
  59578. }
  59579. else {
  59580. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  59581. }
  59582. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  59583. this._screenCoordinates.x = pos.x / this._viewPort.width;
  59584. this._screenCoordinates.y = pos.y / this._viewPort.height;
  59585. if (this.invert)
  59586. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  59587. };
  59588. // Static methods
  59589. /**
  59590. * Creates a default mesh for the Volumeric Light Scattering post-process
  59591. * @param {string} The mesh name
  59592. * @param {BABYLON.Scene} The scene where to create the mesh
  59593. * @return {BABYLON.Mesh} the default mesh
  59594. */
  59595. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  59596. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  59597. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59598. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  59599. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  59600. mesh.material = material;
  59601. return mesh;
  59602. };
  59603. __decorate([
  59604. BABYLON.serializeAsVector3()
  59605. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  59606. __decorate([
  59607. BABYLON.serialize()
  59608. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  59609. __decorate([
  59610. BABYLON.serialize()
  59611. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  59612. __decorate([
  59613. BABYLON.serializeAsMeshReference()
  59614. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  59615. __decorate([
  59616. BABYLON.serialize()
  59617. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  59618. __decorate([
  59619. BABYLON.serialize()
  59620. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  59621. __decorate([
  59622. BABYLON.serialize()
  59623. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  59624. __decorate([
  59625. BABYLON.serialize()
  59626. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  59627. __decorate([
  59628. BABYLON.serialize()
  59629. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  59630. return VolumetricLightScatteringPostProcess;
  59631. }(BABYLON.PostProcess));
  59632. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  59633. })(BABYLON || (BABYLON = {}));
  59634. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  59635. //
  59636. // This post-process allows the modification of rendered colors by using
  59637. // a 'look-up table' (LUT). This effect is also called Color Grading.
  59638. //
  59639. // The object needs to be provided an url to a texture containing the color
  59640. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  59641. // Use an image editing software to tweak the LUT to match your needs.
  59642. //
  59643. // For an example of a color LUT, see here:
  59644. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  59645. // For explanations on color grading, see here:
  59646. // http://udn.epicgames.com/Three/ColorGrading.html
  59647. //
  59648. var BABYLON;
  59649. (function (BABYLON) {
  59650. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  59651. __extends(ColorCorrectionPostProcess, _super);
  59652. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  59653. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  59654. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59655. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  59656. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59657. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59658. _this.onApply = function (effect) {
  59659. effect.setTexture("colorTable", _this._colorTableTexture);
  59660. };
  59661. return _this;
  59662. }
  59663. return ColorCorrectionPostProcess;
  59664. }(BABYLON.PostProcess));
  59665. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  59666. })(BABYLON || (BABYLON = {}));
  59667. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  59668. var BABYLON;
  59669. (function (BABYLON) {
  59670. var TonemappingOperator;
  59671. (function (TonemappingOperator) {
  59672. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  59673. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  59674. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  59675. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  59676. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  59677. ;
  59678. var TonemapPostProcess = /** @class */ (function (_super) {
  59679. __extends(TonemapPostProcess, _super);
  59680. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  59681. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59682. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59683. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  59684. _this._operator = _operator;
  59685. _this.exposureAdjustment = exposureAdjustment;
  59686. var defines = "#define ";
  59687. if (_this._operator === TonemappingOperator.Hable)
  59688. defines += "HABLE_TONEMAPPING";
  59689. else if (_this._operator === TonemappingOperator.Reinhard)
  59690. defines += "REINHARD_TONEMAPPING";
  59691. else if (_this._operator === TonemappingOperator.HejiDawson)
  59692. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  59693. else if (_this._operator === TonemappingOperator.Photographic)
  59694. defines += "PHOTOGRAPHIC_TONEMAPPING";
  59695. //sadly a second call to create the effect.
  59696. _this.updateEffect(defines);
  59697. _this.onApply = function (effect) {
  59698. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  59699. };
  59700. return _this;
  59701. }
  59702. return TonemapPostProcess;
  59703. }(BABYLON.PostProcess));
  59704. BABYLON.TonemapPostProcess = TonemapPostProcess;
  59705. })(BABYLON || (BABYLON = {}));
  59706. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  59707. var BABYLON;
  59708. (function (BABYLON) {
  59709. var DisplayPassPostProcess = /** @class */ (function (_super) {
  59710. __extends(DisplayPassPostProcess, _super);
  59711. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  59712. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  59713. }
  59714. return DisplayPassPostProcess;
  59715. }(BABYLON.PostProcess));
  59716. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  59717. })(BABYLON || (BABYLON = {}));
  59718. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  59719. var BABYLON;
  59720. (function (BABYLON) {
  59721. var HighlightsPostProcess = /** @class */ (function (_super) {
  59722. __extends(HighlightsPostProcess, _super);
  59723. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59724. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59725. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  59726. }
  59727. return HighlightsPostProcess;
  59728. }(BABYLON.PostProcess));
  59729. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  59730. })(BABYLON || (BABYLON = {}));
  59731. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  59732. var BABYLON;
  59733. (function (BABYLON) {
  59734. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  59735. __extends(ImageProcessingPostProcess, _super);
  59736. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59737. if (camera === void 0) { camera = null; }
  59738. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59739. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  59740. _this._fromLinearSpace = true;
  59741. /**
  59742. * Defines cache preventing GC.
  59743. */
  59744. _this._defines = {
  59745. IMAGEPROCESSING: false,
  59746. VIGNETTE: false,
  59747. VIGNETTEBLENDMODEMULTIPLY: false,
  59748. VIGNETTEBLENDMODEOPAQUE: false,
  59749. TONEMAPPING: false,
  59750. CONTRAST: false,
  59751. COLORCURVES: false,
  59752. COLORGRADING: false,
  59753. COLORGRADING3D: false,
  59754. FROMLINEARSPACE: false,
  59755. SAMPLER3DGREENDEPTH: false,
  59756. SAMPLER3DBGRMAP: false,
  59757. IMAGEPROCESSINGPOSTPROCESS: false,
  59758. EXPOSURE: false,
  59759. };
  59760. // Setup the default processing configuration to the scene.
  59761. _this._attachImageProcessingConfiguration(null, true);
  59762. _this.imageProcessingConfiguration.applyByPostProcess = true;
  59763. _this.onApply = function (effect) {
  59764. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  59765. };
  59766. return _this;
  59767. }
  59768. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  59769. /**
  59770. * Gets the image processing configuration used either in this material.
  59771. */
  59772. get: function () {
  59773. return this._imageProcessingConfiguration;
  59774. },
  59775. /**
  59776. * Sets the Default image processing configuration used either in the this material.
  59777. *
  59778. * If sets to null, the scene one is in use.
  59779. */
  59780. set: function (value) {
  59781. this._attachImageProcessingConfiguration(value);
  59782. },
  59783. enumerable: true,
  59784. configurable: true
  59785. });
  59786. /**
  59787. * Attaches a new image processing configuration to the PBR Material.
  59788. * @param configuration
  59789. */
  59790. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  59791. var _this = this;
  59792. if (doNotBuild === void 0) { doNotBuild = false; }
  59793. if (configuration === this._imageProcessingConfiguration) {
  59794. return;
  59795. }
  59796. // Detaches observer.
  59797. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59798. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59799. }
  59800. // Pick the scene configuration if needed.
  59801. if (!configuration) {
  59802. var scene = null;
  59803. var engine = this.getEngine();
  59804. var camera = this.getCamera();
  59805. if (camera) {
  59806. scene = camera.getScene();
  59807. }
  59808. else if (engine && engine.scenes) {
  59809. var scenes = engine.scenes;
  59810. scene = scenes[scenes.length - 1];
  59811. }
  59812. else {
  59813. scene = BABYLON.Engine.LastCreatedScene;
  59814. }
  59815. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  59816. }
  59817. else {
  59818. this._imageProcessingConfiguration = configuration;
  59819. }
  59820. // Attaches observer.
  59821. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  59822. _this._updateParameters();
  59823. });
  59824. // Ensure the effect will be rebuilt.
  59825. if (!doNotBuild) {
  59826. this._updateParameters();
  59827. }
  59828. };
  59829. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  59830. /**
  59831. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59832. */
  59833. get: function () {
  59834. return this.imageProcessingConfiguration.colorCurves;
  59835. },
  59836. /**
  59837. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59838. */
  59839. set: function (value) {
  59840. this.imageProcessingConfiguration.colorCurves = value;
  59841. },
  59842. enumerable: true,
  59843. configurable: true
  59844. });
  59845. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  59846. /**
  59847. * Gets wether the color curves effect is enabled.
  59848. */
  59849. get: function () {
  59850. return this.imageProcessingConfiguration.colorCurvesEnabled;
  59851. },
  59852. /**
  59853. * Sets wether the color curves effect is enabled.
  59854. */
  59855. set: function (value) {
  59856. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  59857. },
  59858. enumerable: true,
  59859. configurable: true
  59860. });
  59861. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  59862. /**
  59863. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59864. */
  59865. get: function () {
  59866. return this.imageProcessingConfiguration.colorGradingTexture;
  59867. },
  59868. /**
  59869. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59870. */
  59871. set: function (value) {
  59872. this.imageProcessingConfiguration.colorGradingTexture = value;
  59873. },
  59874. enumerable: true,
  59875. configurable: true
  59876. });
  59877. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  59878. /**
  59879. * Gets wether the color grading effect is enabled.
  59880. */
  59881. get: function () {
  59882. return this.imageProcessingConfiguration.colorGradingEnabled;
  59883. },
  59884. /**
  59885. * Gets wether the color grading effect is enabled.
  59886. */
  59887. set: function (value) {
  59888. this.imageProcessingConfiguration.colorGradingEnabled = value;
  59889. },
  59890. enumerable: true,
  59891. configurable: true
  59892. });
  59893. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  59894. /**
  59895. * Gets exposure used in the effect.
  59896. */
  59897. get: function () {
  59898. return this.imageProcessingConfiguration.exposure;
  59899. },
  59900. /**
  59901. * Sets exposure used in the effect.
  59902. */
  59903. set: function (value) {
  59904. this.imageProcessingConfiguration.exposure = value;
  59905. },
  59906. enumerable: true,
  59907. configurable: true
  59908. });
  59909. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  59910. /**
  59911. * Gets wether tonemapping is enabled or not.
  59912. */
  59913. get: function () {
  59914. return this._imageProcessingConfiguration.toneMappingEnabled;
  59915. },
  59916. /**
  59917. * Sets wether tonemapping is enabled or not
  59918. */
  59919. set: function (value) {
  59920. this._imageProcessingConfiguration.toneMappingEnabled = value;
  59921. },
  59922. enumerable: true,
  59923. configurable: true
  59924. });
  59925. ;
  59926. ;
  59927. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  59928. /**
  59929. * Gets contrast used in the effect.
  59930. */
  59931. get: function () {
  59932. return this.imageProcessingConfiguration.contrast;
  59933. },
  59934. /**
  59935. * Sets contrast used in the effect.
  59936. */
  59937. set: function (value) {
  59938. this.imageProcessingConfiguration.contrast = value;
  59939. },
  59940. enumerable: true,
  59941. configurable: true
  59942. });
  59943. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  59944. /**
  59945. * Gets Vignette stretch size.
  59946. */
  59947. get: function () {
  59948. return this.imageProcessingConfiguration.vignetteStretch;
  59949. },
  59950. /**
  59951. * Sets Vignette stretch size.
  59952. */
  59953. set: function (value) {
  59954. this.imageProcessingConfiguration.vignetteStretch = value;
  59955. },
  59956. enumerable: true,
  59957. configurable: true
  59958. });
  59959. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  59960. /**
  59961. * Gets Vignette centre X Offset.
  59962. */
  59963. get: function () {
  59964. return this.imageProcessingConfiguration.vignetteCentreX;
  59965. },
  59966. /**
  59967. * Sets Vignette centre X Offset.
  59968. */
  59969. set: function (value) {
  59970. this.imageProcessingConfiguration.vignetteCentreX = value;
  59971. },
  59972. enumerable: true,
  59973. configurable: true
  59974. });
  59975. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  59976. /**
  59977. * Gets Vignette centre Y Offset.
  59978. */
  59979. get: function () {
  59980. return this.imageProcessingConfiguration.vignetteCentreY;
  59981. },
  59982. /**
  59983. * Sets Vignette centre Y Offset.
  59984. */
  59985. set: function (value) {
  59986. this.imageProcessingConfiguration.vignetteCentreY = value;
  59987. },
  59988. enumerable: true,
  59989. configurable: true
  59990. });
  59991. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  59992. /**
  59993. * Gets Vignette weight or intensity of the vignette effect.
  59994. */
  59995. get: function () {
  59996. return this.imageProcessingConfiguration.vignetteWeight;
  59997. },
  59998. /**
  59999. * Sets Vignette weight or intensity of the vignette effect.
  60000. */
  60001. set: function (value) {
  60002. this.imageProcessingConfiguration.vignetteWeight = value;
  60003. },
  60004. enumerable: true,
  60005. configurable: true
  60006. });
  60007. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  60008. /**
  60009. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60010. * if vignetteEnabled is set to true.
  60011. */
  60012. get: function () {
  60013. return this.imageProcessingConfiguration.vignetteColor;
  60014. },
  60015. /**
  60016. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60017. * if vignetteEnabled is set to true.
  60018. */
  60019. set: function (value) {
  60020. this.imageProcessingConfiguration.vignetteColor = value;
  60021. },
  60022. enumerable: true,
  60023. configurable: true
  60024. });
  60025. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  60026. /**
  60027. * Gets Camera field of view used by the Vignette effect.
  60028. */
  60029. get: function () {
  60030. return this.imageProcessingConfiguration.vignetteCameraFov;
  60031. },
  60032. /**
  60033. * Sets Camera field of view used by the Vignette effect.
  60034. */
  60035. set: function (value) {
  60036. this.imageProcessingConfiguration.vignetteCameraFov = value;
  60037. },
  60038. enumerable: true,
  60039. configurable: true
  60040. });
  60041. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  60042. /**
  60043. * Gets the vignette blend mode allowing different kind of effect.
  60044. */
  60045. get: function () {
  60046. return this.imageProcessingConfiguration.vignetteBlendMode;
  60047. },
  60048. /**
  60049. * Sets the vignette blend mode allowing different kind of effect.
  60050. */
  60051. set: function (value) {
  60052. this.imageProcessingConfiguration.vignetteBlendMode = value;
  60053. },
  60054. enumerable: true,
  60055. configurable: true
  60056. });
  60057. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  60058. /**
  60059. * Gets wether the vignette effect is enabled.
  60060. */
  60061. get: function () {
  60062. return this.imageProcessingConfiguration.vignetteEnabled;
  60063. },
  60064. /**
  60065. * Sets wether the vignette effect is enabled.
  60066. */
  60067. set: function (value) {
  60068. this.imageProcessingConfiguration.vignetteEnabled = value;
  60069. },
  60070. enumerable: true,
  60071. configurable: true
  60072. });
  60073. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  60074. /**
  60075. * Gets wether the input of the processing is in Gamma or Linear Space.
  60076. */
  60077. get: function () {
  60078. return this._fromLinearSpace;
  60079. },
  60080. /**
  60081. * Sets wether the input of the processing is in Gamma or Linear Space.
  60082. */
  60083. set: function (value) {
  60084. if (this._fromLinearSpace === value) {
  60085. return;
  60086. }
  60087. this._fromLinearSpace = value;
  60088. this._updateParameters();
  60089. },
  60090. enumerable: true,
  60091. configurable: true
  60092. });
  60093. ImageProcessingPostProcess.prototype.getClassName = function () {
  60094. return "ImageProcessingPostProcess";
  60095. };
  60096. ImageProcessingPostProcess.prototype._updateParameters = function () {
  60097. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  60098. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  60099. var defines = "";
  60100. for (var define in this._defines) {
  60101. if (this._defines[define]) {
  60102. defines += "#define " + define + ";\r\n";
  60103. }
  60104. }
  60105. var samplers = ["textureSampler"];
  60106. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  60107. var uniforms = ["scale"];
  60108. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  60109. this.updateEffect(defines, uniforms, samplers);
  60110. };
  60111. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  60112. _super.prototype.dispose.call(this, camera);
  60113. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60114. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60115. }
  60116. this.imageProcessingConfiguration.applyByPostProcess = false;
  60117. };
  60118. __decorate([
  60119. BABYLON.serialize()
  60120. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  60121. return ImageProcessingPostProcess;
  60122. }(BABYLON.PostProcess));
  60123. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  60124. })(BABYLON || (BABYLON = {}));
  60125. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  60126. var BABYLON;
  60127. (function (BABYLON) {
  60128. var BlurPostProcess = /** @class */ (function (_super) {
  60129. __extends(BlurPostProcess, _super);
  60130. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  60131. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60132. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60133. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  60134. _this.direction = direction;
  60135. _this._packedFloat = false;
  60136. _this.onApplyObservable.add(function (effect) {
  60137. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  60138. });
  60139. _this.kernel = kernel;
  60140. return _this;
  60141. }
  60142. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  60143. /**
  60144. * Gets the length in pixels of the blur sample region
  60145. */
  60146. get: function () {
  60147. return this._idealKernel;
  60148. },
  60149. /**
  60150. * Sets the length in pixels of the blur sample region
  60151. */
  60152. set: function (v) {
  60153. if (this._idealKernel === v) {
  60154. return;
  60155. }
  60156. v = Math.max(v, 1);
  60157. this._idealKernel = v;
  60158. this._kernel = this._nearestBestKernel(v);
  60159. this._updateParameters();
  60160. },
  60161. enumerable: true,
  60162. configurable: true
  60163. });
  60164. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60165. /**
  60166. * Gets wether or not the blur is unpacking/repacking floats
  60167. */
  60168. get: function () {
  60169. return this._packedFloat;
  60170. },
  60171. /**
  60172. * Sets wether or not the blur needs to unpack/repack floats
  60173. */
  60174. set: function (v) {
  60175. if (this._packedFloat === v) {
  60176. return;
  60177. }
  60178. this._packedFloat = v;
  60179. this._updateParameters();
  60180. },
  60181. enumerable: true,
  60182. configurable: true
  60183. });
  60184. BlurPostProcess.prototype._updateParameters = function () {
  60185. // Generate sampling offsets and weights
  60186. var N = this._kernel;
  60187. var centerIndex = (N - 1) / 2;
  60188. // Generate Gaussian sampling weights over kernel
  60189. var offsets = [];
  60190. var weights = [];
  60191. var totalWeight = 0;
  60192. for (var i = 0; i < N; i++) {
  60193. var u = i / (N - 1);
  60194. var w = this._gaussianWeight(u * 2.0 - 1);
  60195. offsets[i] = (i - centerIndex);
  60196. weights[i] = w;
  60197. totalWeight += w;
  60198. }
  60199. // Normalize weights
  60200. for (var i = 0; i < weights.length; i++) {
  60201. weights[i] /= totalWeight;
  60202. }
  60203. // Optimize: combine samples to take advantage of hardware linear sampling
  60204. // Walk from left to center, combining pairs (symmetrically)
  60205. var linearSamplingWeights = [];
  60206. var linearSamplingOffsets = [];
  60207. var linearSamplingMap = [];
  60208. for (var i = 0; i <= centerIndex; i += 2) {
  60209. var j = Math.min(i + 1, Math.floor(centerIndex));
  60210. var singleCenterSample = i === j;
  60211. if (singleCenterSample) {
  60212. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60213. }
  60214. else {
  60215. var sharedCell = j === centerIndex;
  60216. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  60217. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  60218. if (offsetLinear === 0) {
  60219. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60220. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  60221. }
  60222. else {
  60223. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  60224. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  60225. }
  60226. }
  60227. }
  60228. for (var i = 0; i < linearSamplingMap.length; i++) {
  60229. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  60230. linearSamplingWeights[i] = linearSamplingMap[i].w;
  60231. }
  60232. // Replace with optimized
  60233. offsets = linearSamplingOffsets;
  60234. weights = linearSamplingWeights;
  60235. // Generate shaders
  60236. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  60237. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  60238. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  60239. var defines = "";
  60240. for (var i = 0; i < varyingCount; i++) {
  60241. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  60242. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  60243. }
  60244. var depCount = 0;
  60245. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  60246. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  60247. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  60248. depCount++;
  60249. }
  60250. if (this.packedFloat) {
  60251. defines += "#define PACKEDFLOAT 1";
  60252. }
  60253. this.updateEffect(defines, null, null, {
  60254. varyingCount: varyingCount,
  60255. depCount: depCount
  60256. });
  60257. };
  60258. /**
  60259. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  60260. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  60261. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  60262. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  60263. * The gaps between physical kernels are compensated for in the weighting of the samples
  60264. * @param idealKernel Ideal blur kernel.
  60265. * @return Nearest best kernel.
  60266. */
  60267. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  60268. var v = Math.round(idealKernel);
  60269. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  60270. var k = _a[_i];
  60271. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  60272. return Math.max(k, 3);
  60273. }
  60274. }
  60275. return Math.max(v, 3);
  60276. };
  60277. /**
  60278. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  60279. * @param x The point on the Gaussian distribution to sample.
  60280. * @return the value of the Gaussian function at x.
  60281. */
  60282. BlurPostProcess.prototype._gaussianWeight = function (x) {
  60283. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  60284. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  60285. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  60286. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  60287. // truncated at around 1.3% of peak strength.
  60288. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  60289. var sigma = (1 / 3);
  60290. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  60291. var exponent = -((x * x) / (2.0 * sigma * sigma));
  60292. var weight = (1.0 / denominator) * Math.exp(exponent);
  60293. return weight;
  60294. };
  60295. /**
  60296. * Generates a string that can be used as a floating point number in GLSL.
  60297. * @param x Value to print.
  60298. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  60299. * @return GLSL float string.
  60300. */
  60301. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  60302. if (decimalFigures === void 0) { decimalFigures = 8; }
  60303. return x.toFixed(decimalFigures).replace(/0+$/, '');
  60304. };
  60305. return BlurPostProcess;
  60306. }(BABYLON.PostProcess));
  60307. BABYLON.BlurPostProcess = BlurPostProcess;
  60308. })(BABYLON || (BABYLON = {}));
  60309. //# sourceMappingURL=babylon.blurPostProcess.js.map
  60310. var BABYLON;
  60311. (function (BABYLON) {
  60312. var Bone = /** @class */ (function (_super) {
  60313. __extends(Bone, _super);
  60314. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  60315. if (parentBone === void 0) { parentBone = null; }
  60316. if (localMatrix === void 0) { localMatrix = null; }
  60317. if (restPose === void 0) { restPose = null; }
  60318. if (baseMatrix === void 0) { baseMatrix = null; }
  60319. if (index === void 0) { index = null; }
  60320. var _this = _super.call(this, name, skeleton.getScene()) || this;
  60321. _this.name = name;
  60322. _this.children = new Array();
  60323. _this.animations = new Array();
  60324. // Set this value to map this bone to a different index in the transform matrices.
  60325. // Set this value to -1 to exclude the bone from the transform matrices.
  60326. _this._index = null;
  60327. _this._worldTransform = new BABYLON.Matrix();
  60328. _this._absoluteTransform = new BABYLON.Matrix();
  60329. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  60330. _this._scaleMatrix = BABYLON.Matrix.Identity();
  60331. _this._scaleVector = BABYLON.Vector3.One();
  60332. _this._negateScaleChildren = BABYLON.Vector3.One();
  60333. _this._scalingDeterminant = 1;
  60334. _this._skeleton = skeleton;
  60335. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  60336. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  60337. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  60338. _this._index = index;
  60339. skeleton.bones.push(_this);
  60340. _this.setParent(parentBone, false);
  60341. _this._updateDifferenceMatrix();
  60342. return _this;
  60343. }
  60344. Object.defineProperty(Bone.prototype, "_matrix", {
  60345. get: function () {
  60346. return this._localMatrix;
  60347. },
  60348. set: function (val) {
  60349. if (this._localMatrix) {
  60350. this._localMatrix.copyFrom(val);
  60351. }
  60352. else {
  60353. this._localMatrix = val;
  60354. }
  60355. },
  60356. enumerable: true,
  60357. configurable: true
  60358. });
  60359. // Members
  60360. Bone.prototype.getSkeleton = function () {
  60361. return this._skeleton;
  60362. };
  60363. Bone.prototype.getParent = function () {
  60364. return this._parent;
  60365. };
  60366. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  60367. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60368. if (this._parent === parent) {
  60369. return;
  60370. }
  60371. if (this._parent) {
  60372. var index = this._parent.children.indexOf(this);
  60373. if (index !== -1) {
  60374. this._parent.children.splice(index, 1);
  60375. }
  60376. }
  60377. this._parent = parent;
  60378. if (this._parent) {
  60379. this._parent.children.push(this);
  60380. }
  60381. if (updateDifferenceMatrix) {
  60382. this._updateDifferenceMatrix();
  60383. }
  60384. };
  60385. Bone.prototype.getLocalMatrix = function () {
  60386. return this._localMatrix;
  60387. };
  60388. Bone.prototype.getBaseMatrix = function () {
  60389. return this._baseMatrix;
  60390. };
  60391. Bone.prototype.getRestPose = function () {
  60392. return this._restPose;
  60393. };
  60394. Bone.prototype.returnToRest = function () {
  60395. this.updateMatrix(this._restPose.clone());
  60396. };
  60397. Bone.prototype.getWorldMatrix = function () {
  60398. return this._worldTransform;
  60399. };
  60400. Bone.prototype.getInvertedAbsoluteTransform = function () {
  60401. return this._invertedAbsoluteTransform;
  60402. };
  60403. Bone.prototype.getAbsoluteTransform = function () {
  60404. return this._absoluteTransform;
  60405. };
  60406. Object.defineProperty(Bone.prototype, "position", {
  60407. // Properties (matches AbstractMesh properties)
  60408. get: function () {
  60409. return this.getPosition();
  60410. },
  60411. set: function (newPosition) {
  60412. this.setPosition(newPosition);
  60413. },
  60414. enumerable: true,
  60415. configurable: true
  60416. });
  60417. Object.defineProperty(Bone.prototype, "rotation", {
  60418. get: function () {
  60419. return this.getRotation();
  60420. },
  60421. set: function (newRotation) {
  60422. this.setRotation(newRotation);
  60423. },
  60424. enumerable: true,
  60425. configurable: true
  60426. });
  60427. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  60428. get: function () {
  60429. return this.getRotationQuaternion();
  60430. },
  60431. set: function (newRotation) {
  60432. this.setRotationQuaternion(newRotation);
  60433. },
  60434. enumerable: true,
  60435. configurable: true
  60436. });
  60437. Object.defineProperty(Bone.prototype, "scaling", {
  60438. get: function () {
  60439. return this.getScale();
  60440. },
  60441. set: function (newScaling) {
  60442. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  60443. },
  60444. enumerable: true,
  60445. configurable: true
  60446. });
  60447. // Methods
  60448. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  60449. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60450. this._baseMatrix = matrix.clone();
  60451. this._localMatrix = matrix.clone();
  60452. this._skeleton._markAsDirty();
  60453. if (updateDifferenceMatrix) {
  60454. this._updateDifferenceMatrix();
  60455. }
  60456. };
  60457. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  60458. if (!rootMatrix) {
  60459. rootMatrix = this._baseMatrix;
  60460. }
  60461. if (this._parent) {
  60462. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60463. }
  60464. else {
  60465. this._absoluteTransform.copyFrom(rootMatrix);
  60466. }
  60467. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  60468. for (var index = 0; index < this.children.length; index++) {
  60469. this.children[index]._updateDifferenceMatrix();
  60470. }
  60471. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  60472. };
  60473. Bone.prototype.markAsDirty = function () {
  60474. this._currentRenderId++;
  60475. this._skeleton._markAsDirty();
  60476. };
  60477. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  60478. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60479. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  60480. // all animation may be coming from a library skeleton, so may need to create animation
  60481. if (this.animations.length === 0) {
  60482. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  60483. this.animations[0].setKeys([]);
  60484. }
  60485. // get animation info / verify there is such a range from the source bone
  60486. var sourceRange = source.animations[0].getRange(rangeName);
  60487. if (!sourceRange) {
  60488. return false;
  60489. }
  60490. var from = sourceRange.from;
  60491. var to = sourceRange.to;
  60492. var sourceKeys = source.animations[0].getKeys();
  60493. // rescaling prep
  60494. var sourceBoneLength = source.length;
  60495. var sourceParent = source.getParent();
  60496. var parent = this.getParent();
  60497. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  60498. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  60499. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  60500. var destKeys = this.animations[0].getKeys();
  60501. // loop vars declaration
  60502. var orig;
  60503. var origTranslation;
  60504. var mat;
  60505. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  60506. orig = sourceKeys[key];
  60507. if (orig.frame >= from && orig.frame <= to) {
  60508. if (rescaleAsRequired) {
  60509. mat = orig.value.clone();
  60510. // scale based on parent ratio, when bone has parent
  60511. if (parentScalingReqd) {
  60512. origTranslation = mat.getTranslation();
  60513. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  60514. // scale based on skeleton dimension ratio when root bone, and value is passed
  60515. }
  60516. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  60517. origTranslation = mat.getTranslation();
  60518. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  60519. // use original when root bone, and no data for skelDimensionsRatio
  60520. }
  60521. else {
  60522. mat = orig.value;
  60523. }
  60524. }
  60525. else {
  60526. mat = orig.value;
  60527. }
  60528. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  60529. }
  60530. }
  60531. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  60532. return true;
  60533. };
  60534. /**
  60535. * Translate the bone in local or world space.
  60536. * @param vec The amount to translate the bone.
  60537. * @param space The space that the translation is in.
  60538. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60539. */
  60540. Bone.prototype.translate = function (vec, space, mesh) {
  60541. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60542. var lm = this.getLocalMatrix();
  60543. if (space == BABYLON.Space.LOCAL) {
  60544. lm.m[12] += vec.x;
  60545. lm.m[13] += vec.y;
  60546. lm.m[14] += vec.z;
  60547. }
  60548. else {
  60549. var wm = null;
  60550. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60551. if (mesh) {
  60552. wm = mesh.getWorldMatrix();
  60553. }
  60554. this._skeleton.computeAbsoluteTransforms();
  60555. var tmat = Bone._tmpMats[0];
  60556. var tvec = Bone._tmpVecs[0];
  60557. if (this._parent) {
  60558. if (mesh && wm) {
  60559. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60560. tmat.multiplyToRef(wm, tmat);
  60561. }
  60562. else {
  60563. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60564. }
  60565. }
  60566. tmat.m[12] = 0;
  60567. tmat.m[13] = 0;
  60568. tmat.m[14] = 0;
  60569. tmat.invert();
  60570. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  60571. lm.m[12] += tvec.x;
  60572. lm.m[13] += tvec.y;
  60573. lm.m[14] += tvec.z;
  60574. }
  60575. this.markAsDirty();
  60576. };
  60577. /**
  60578. * Set the postion of the bone in local or world space.
  60579. * @param position The position to set the bone.
  60580. * @param space The space that the position is in.
  60581. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60582. */
  60583. Bone.prototype.setPosition = function (position, space, mesh) {
  60584. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60585. var lm = this.getLocalMatrix();
  60586. if (space == BABYLON.Space.LOCAL) {
  60587. lm.m[12] = position.x;
  60588. lm.m[13] = position.y;
  60589. lm.m[14] = position.z;
  60590. }
  60591. else {
  60592. var wm = null;
  60593. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60594. if (mesh) {
  60595. wm = mesh.getWorldMatrix();
  60596. }
  60597. this._skeleton.computeAbsoluteTransforms();
  60598. var tmat = Bone._tmpMats[0];
  60599. var vec = Bone._tmpVecs[0];
  60600. if (this._parent) {
  60601. if (mesh && wm) {
  60602. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60603. tmat.multiplyToRef(wm, tmat);
  60604. }
  60605. else {
  60606. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60607. }
  60608. }
  60609. tmat.invert();
  60610. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  60611. lm.m[12] = vec.x;
  60612. lm.m[13] = vec.y;
  60613. lm.m[14] = vec.z;
  60614. }
  60615. this.markAsDirty();
  60616. };
  60617. /**
  60618. * Set the absolute postion of the bone (world space).
  60619. * @param position The position to set the bone.
  60620. * @param mesh The mesh that this bone is attached to.
  60621. */
  60622. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  60623. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  60624. };
  60625. /**
  60626. * Set the scale of the bone on the x, y and z axes.
  60627. * @param x The scale of the bone on the x axis.
  60628. * @param x The scale of the bone on the y axis.
  60629. * @param z The scale of the bone on the z axis.
  60630. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60631. */
  60632. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  60633. if (scaleChildren === void 0) { scaleChildren = false; }
  60634. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  60635. if (!scaleChildren) {
  60636. this._negateScaleChildren.x = 1 / x;
  60637. this._negateScaleChildren.y = 1 / y;
  60638. this._negateScaleChildren.z = 1 / z;
  60639. }
  60640. this._syncScaleVector();
  60641. }
  60642. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  60643. };
  60644. /**
  60645. * Scale the bone on the x, y and z axes.
  60646. * @param x The amount to scale the bone on the x axis.
  60647. * @param x The amount to scale the bone on the y axis.
  60648. * @param z The amount to scale the bone on the z axis.
  60649. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60650. */
  60651. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  60652. if (scaleChildren === void 0) { scaleChildren = false; }
  60653. var locMat = this.getLocalMatrix();
  60654. var origLocMat = Bone._tmpMats[0];
  60655. origLocMat.copyFrom(locMat);
  60656. var origLocMatInv = Bone._tmpMats[1];
  60657. origLocMatInv.copyFrom(origLocMat);
  60658. origLocMatInv.invert();
  60659. var scaleMat = Bone._tmpMats[2];
  60660. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  60661. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  60662. this._scaleVector.x *= x;
  60663. this._scaleVector.y *= y;
  60664. this._scaleVector.z *= z;
  60665. locMat.multiplyToRef(origLocMatInv, locMat);
  60666. locMat.multiplyToRef(scaleMat, locMat);
  60667. locMat.multiplyToRef(origLocMat, locMat);
  60668. var parent = this.getParent();
  60669. if (parent) {
  60670. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  60671. }
  60672. else {
  60673. this.getAbsoluteTransform().copyFrom(locMat);
  60674. }
  60675. var len = this.children.length;
  60676. scaleMat.invert();
  60677. for (var i = 0; i < len; i++) {
  60678. var child = this.children[i];
  60679. var cm = child.getLocalMatrix();
  60680. cm.multiplyToRef(scaleMat, cm);
  60681. var lm = child.getLocalMatrix();
  60682. lm.m[12] *= x;
  60683. lm.m[13] *= y;
  60684. lm.m[14] *= z;
  60685. }
  60686. this.computeAbsoluteTransforms();
  60687. if (scaleChildren) {
  60688. for (var i = 0; i < len; i++) {
  60689. this.children[i].scale(x, y, z, scaleChildren);
  60690. }
  60691. }
  60692. this.markAsDirty();
  60693. };
  60694. /**
  60695. * Set the yaw, pitch, and roll of the bone in local or world space.
  60696. * @param yaw The rotation of the bone on the y axis.
  60697. * @param pitch The rotation of the bone on the x axis.
  60698. * @param roll The rotation of the bone on the z axis.
  60699. * @param space The space that the axes of rotation are in.
  60700. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60701. */
  60702. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  60703. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60704. var rotMat = Bone._tmpMats[0];
  60705. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  60706. var rotMatInv = Bone._tmpMats[1];
  60707. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60708. rotMatInv.multiplyToRef(rotMat, rotMat);
  60709. this._rotateWithMatrix(rotMat, space, mesh);
  60710. };
  60711. /**
  60712. * Rotate the bone on an axis in local or world space.
  60713. * @param axis The axis to rotate the bone on.
  60714. * @param amount The amount to rotate the bone.
  60715. * @param space The space that the axis is in.
  60716. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60717. */
  60718. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  60719. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60720. var rmat = Bone._tmpMats[0];
  60721. rmat.m[12] = 0;
  60722. rmat.m[13] = 0;
  60723. rmat.m[14] = 0;
  60724. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  60725. this._rotateWithMatrix(rmat, space, mesh);
  60726. };
  60727. /**
  60728. * Set the rotation of the bone to a particular axis angle in local or world space.
  60729. * @param axis The axis to rotate the bone on.
  60730. * @param angle The angle that the bone should be rotated to.
  60731. * @param space The space that the axis is in.
  60732. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60733. */
  60734. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  60735. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60736. var rotMat = Bone._tmpMats[0];
  60737. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  60738. var rotMatInv = Bone._tmpMats[1];
  60739. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60740. rotMatInv.multiplyToRef(rotMat, rotMat);
  60741. this._rotateWithMatrix(rotMat, space, mesh);
  60742. };
  60743. /**
  60744. * Set the euler rotation of the bone in local of world space.
  60745. * @param rotation The euler rotation that the bone should be set to.
  60746. * @param space The space that the rotation is in.
  60747. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60748. */
  60749. Bone.prototype.setRotation = function (rotation, space, mesh) {
  60750. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60751. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  60752. };
  60753. /**
  60754. * Set the quaternion rotation of the bone in local of world space.
  60755. * @param quat The quaternion rotation that the bone should be set to.
  60756. * @param space The space that the rotation is in.
  60757. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60758. */
  60759. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  60760. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60761. var rotMatInv = Bone._tmpMats[0];
  60762. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60763. var rotMat = Bone._tmpMats[1];
  60764. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  60765. rotMatInv.multiplyToRef(rotMat, rotMat);
  60766. this._rotateWithMatrix(rotMat, space, mesh);
  60767. };
  60768. /**
  60769. * Set the rotation matrix of the bone in local of world space.
  60770. * @param rotMat The rotation matrix that the bone should be set to.
  60771. * @param space The space that the rotation is in.
  60772. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60773. */
  60774. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  60775. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60776. var rotMatInv = Bone._tmpMats[0];
  60777. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60778. var rotMat2 = Bone._tmpMats[1];
  60779. rotMat2.copyFrom(rotMat);
  60780. rotMatInv.multiplyToRef(rotMat, rotMat2);
  60781. this._rotateWithMatrix(rotMat2, space, mesh);
  60782. };
  60783. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  60784. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60785. var lmat = this.getLocalMatrix();
  60786. var lx = lmat.m[12];
  60787. var ly = lmat.m[13];
  60788. var lz = lmat.m[14];
  60789. var parent = this.getParent();
  60790. var parentScale = Bone._tmpMats[3];
  60791. var parentScaleInv = Bone._tmpMats[4];
  60792. if (parent) {
  60793. if (space == BABYLON.Space.WORLD) {
  60794. if (mesh) {
  60795. parentScale.copyFrom(mesh.getWorldMatrix());
  60796. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  60797. }
  60798. else {
  60799. parentScale.copyFrom(parent.getAbsoluteTransform());
  60800. }
  60801. }
  60802. else {
  60803. parentScale = parent._scaleMatrix;
  60804. }
  60805. parentScaleInv.copyFrom(parentScale);
  60806. parentScaleInv.invert();
  60807. lmat.multiplyToRef(parentScale, lmat);
  60808. lmat.multiplyToRef(rmat, lmat);
  60809. lmat.multiplyToRef(parentScaleInv, lmat);
  60810. }
  60811. else {
  60812. if (space == BABYLON.Space.WORLD && mesh) {
  60813. parentScale.copyFrom(mesh.getWorldMatrix());
  60814. parentScaleInv.copyFrom(parentScale);
  60815. parentScaleInv.invert();
  60816. lmat.multiplyToRef(parentScale, lmat);
  60817. lmat.multiplyToRef(rmat, lmat);
  60818. lmat.multiplyToRef(parentScaleInv, lmat);
  60819. }
  60820. else {
  60821. lmat.multiplyToRef(rmat, lmat);
  60822. }
  60823. }
  60824. lmat.m[12] = lx;
  60825. lmat.m[13] = ly;
  60826. lmat.m[14] = lz;
  60827. this.computeAbsoluteTransforms();
  60828. this.markAsDirty();
  60829. };
  60830. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  60831. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60832. if (space == BABYLON.Space.WORLD) {
  60833. var scaleMatrix = Bone._tmpMats[2];
  60834. scaleMatrix.copyFrom(this._scaleMatrix);
  60835. rotMatInv.copyFrom(this.getAbsoluteTransform());
  60836. if (mesh) {
  60837. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  60838. var meshScale = Bone._tmpMats[3];
  60839. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  60840. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  60841. }
  60842. rotMatInv.invert();
  60843. scaleMatrix.m[0] *= this._scalingDeterminant;
  60844. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60845. }
  60846. else {
  60847. rotMatInv.copyFrom(this.getLocalMatrix());
  60848. rotMatInv.invert();
  60849. var scaleMatrix = Bone._tmpMats[2];
  60850. scaleMatrix.copyFrom(this._scaleMatrix);
  60851. if (this._parent) {
  60852. var pscaleMatrix = Bone._tmpMats[3];
  60853. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  60854. pscaleMatrix.invert();
  60855. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  60856. }
  60857. else {
  60858. scaleMatrix.m[0] *= this._scalingDeterminant;
  60859. }
  60860. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60861. }
  60862. };
  60863. /**
  60864. * Get the scale of the bone
  60865. * @returns the scale of the bone
  60866. */
  60867. Bone.prototype.getScale = function () {
  60868. return this._scaleVector.clone();
  60869. };
  60870. /**
  60871. * Copy the scale of the bone to a vector3.
  60872. * @param result The vector3 to copy the scale to
  60873. */
  60874. Bone.prototype.getScaleToRef = function (result) {
  60875. result.copyFrom(this._scaleVector);
  60876. };
  60877. /**
  60878. * Get the position of the bone in local or world space.
  60879. * @param space The space that the returned position is in.
  60880. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60881. * @returns The position of the bone
  60882. */
  60883. Bone.prototype.getPosition = function (space, mesh) {
  60884. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60885. if (mesh === void 0) { mesh = null; }
  60886. var pos = BABYLON.Vector3.Zero();
  60887. this.getPositionToRef(space, mesh, pos);
  60888. return pos;
  60889. };
  60890. /**
  60891. * Copy the position of the bone to a vector3 in local or world space.
  60892. * @param space The space that the returned position is in.
  60893. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60894. * @param result The vector3 to copy the position to.
  60895. */
  60896. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  60897. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60898. if (space == BABYLON.Space.LOCAL) {
  60899. var lm = this.getLocalMatrix();
  60900. result.x = lm.m[12];
  60901. result.y = lm.m[13];
  60902. result.z = lm.m[14];
  60903. }
  60904. else {
  60905. var wm = null;
  60906. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60907. if (mesh) {
  60908. wm = mesh.getWorldMatrix();
  60909. }
  60910. this._skeleton.computeAbsoluteTransforms();
  60911. var tmat = Bone._tmpMats[0];
  60912. if (mesh && wm) {
  60913. tmat.copyFrom(this.getAbsoluteTransform());
  60914. tmat.multiplyToRef(wm, tmat);
  60915. }
  60916. else {
  60917. tmat = this.getAbsoluteTransform();
  60918. }
  60919. result.x = tmat.m[12];
  60920. result.y = tmat.m[13];
  60921. result.z = tmat.m[14];
  60922. }
  60923. };
  60924. /**
  60925. * Get the absolute position of the bone (world space).
  60926. * @param mesh The mesh that this bone is attached to.
  60927. * @returns The absolute position of the bone
  60928. */
  60929. Bone.prototype.getAbsolutePosition = function (mesh) {
  60930. if (mesh === void 0) { mesh = null; }
  60931. var pos = BABYLON.Vector3.Zero();
  60932. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  60933. return pos;
  60934. };
  60935. /**
  60936. * Copy the absolute position of the bone (world space) to the result param.
  60937. * @param mesh The mesh that this bone is attached to.
  60938. * @param result The vector3 to copy the absolute position to.
  60939. */
  60940. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  60941. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  60942. };
  60943. /**
  60944. * Compute the absolute transforms of this bone and its children.
  60945. */
  60946. Bone.prototype.computeAbsoluteTransforms = function () {
  60947. if (this._parent) {
  60948. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60949. }
  60950. else {
  60951. this._absoluteTransform.copyFrom(this._localMatrix);
  60952. var poseMatrix = this._skeleton.getPoseMatrix();
  60953. if (poseMatrix) {
  60954. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  60955. }
  60956. }
  60957. var children = this.children;
  60958. var len = children.length;
  60959. for (var i = 0; i < len; i++) {
  60960. children[i].computeAbsoluteTransforms();
  60961. }
  60962. };
  60963. Bone.prototype._syncScaleVector = function () {
  60964. var lm = this.getLocalMatrix();
  60965. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  60966. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  60967. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  60968. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  60969. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  60970. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  60971. this._scaleVector.x = xs * Math.sqrt(xsq);
  60972. this._scaleVector.y = ys * Math.sqrt(ysq);
  60973. this._scaleVector.z = zs * Math.sqrt(zsq);
  60974. if (this._parent) {
  60975. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  60976. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  60977. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  60978. }
  60979. 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);
  60980. };
  60981. /**
  60982. * Get the world direction from an axis that is in the local space of the bone.
  60983. * @param localAxis The local direction that is used to compute the world direction.
  60984. * @param mesh The mesh that this bone is attached to.
  60985. * @returns The world direction
  60986. */
  60987. Bone.prototype.getDirection = function (localAxis, mesh) {
  60988. if (mesh === void 0) { mesh = null; }
  60989. var result = BABYLON.Vector3.Zero();
  60990. this.getDirectionToRef(localAxis, mesh, result);
  60991. return result;
  60992. };
  60993. /**
  60994. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  60995. * @param localAxis The local direction that is used to compute the world direction.
  60996. * @param mesh The mesh that this bone is attached to.
  60997. * @param result The vector3 that the world direction will be copied to.
  60998. */
  60999. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  61000. if (mesh === void 0) { mesh = null; }
  61001. var wm = null;
  61002. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61003. if (mesh) {
  61004. wm = mesh.getWorldMatrix();
  61005. }
  61006. this._skeleton.computeAbsoluteTransforms();
  61007. var mat = Bone._tmpMats[0];
  61008. mat.copyFrom(this.getAbsoluteTransform());
  61009. if (mesh && wm) {
  61010. mat.multiplyToRef(wm, mat);
  61011. }
  61012. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  61013. result.normalize();
  61014. };
  61015. /**
  61016. * Get the euler rotation of the bone in local or world space.
  61017. * @param space The space that the rotation should be in.
  61018. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61019. * @returns The euler rotation
  61020. */
  61021. Bone.prototype.getRotation = function (space, mesh) {
  61022. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61023. if (mesh === void 0) { mesh = null; }
  61024. var result = BABYLON.Vector3.Zero();
  61025. this.getRotationToRef(space, mesh, result);
  61026. return result;
  61027. };
  61028. /**
  61029. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  61030. * @param space The space that the rotation should be in.
  61031. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61032. * @param result The vector3 that the rotation should be copied to.
  61033. */
  61034. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  61035. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61036. if (mesh === void 0) { mesh = null; }
  61037. var quat = Bone._tmpQuat;
  61038. this.getRotationQuaternionToRef(space, mesh, quat);
  61039. quat.toEulerAnglesToRef(result);
  61040. };
  61041. /**
  61042. * Get the quaternion rotation of the bone in either local or world space.
  61043. * @param space The space that the rotation should be in.
  61044. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61045. * @returns The quaternion rotation
  61046. */
  61047. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  61048. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61049. if (mesh === void 0) { mesh = null; }
  61050. var result = BABYLON.Quaternion.Identity();
  61051. this.getRotationQuaternionToRef(space, mesh, result);
  61052. return result;
  61053. };
  61054. /**
  61055. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  61056. * @param space The space that the rotation should be in.
  61057. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61058. * @param result The quaternion that the rotation should be copied to.
  61059. */
  61060. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  61061. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61062. if (mesh === void 0) { mesh = null; }
  61063. if (space == BABYLON.Space.LOCAL) {
  61064. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61065. }
  61066. else {
  61067. var mat = Bone._tmpMats[0];
  61068. var amat = this.getAbsoluteTransform();
  61069. if (mesh) {
  61070. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61071. }
  61072. else {
  61073. mat.copyFrom(amat);
  61074. }
  61075. mat.m[0] *= this._scalingDeterminant;
  61076. mat.m[1] *= this._scalingDeterminant;
  61077. mat.m[2] *= this._scalingDeterminant;
  61078. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61079. }
  61080. };
  61081. /**
  61082. * Get the rotation matrix of the bone in local or world space.
  61083. * @param space The space that the rotation should be in.
  61084. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61085. * @returns The rotation matrix
  61086. */
  61087. Bone.prototype.getRotationMatrix = function (space, mesh) {
  61088. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61089. var result = BABYLON.Matrix.Identity();
  61090. this.getRotationMatrixToRef(space, mesh, result);
  61091. return result;
  61092. };
  61093. /**
  61094. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  61095. * @param space The space that the rotation should be in.
  61096. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61097. * @param result The quaternion that the rotation should be copied to.
  61098. */
  61099. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  61100. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61101. if (space == BABYLON.Space.LOCAL) {
  61102. this.getLocalMatrix().getRotationMatrixToRef(result);
  61103. }
  61104. else {
  61105. var mat = Bone._tmpMats[0];
  61106. var amat = this.getAbsoluteTransform();
  61107. if (mesh) {
  61108. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61109. }
  61110. else {
  61111. mat.copyFrom(amat);
  61112. }
  61113. mat.m[0] *= this._scalingDeterminant;
  61114. mat.m[1] *= this._scalingDeterminant;
  61115. mat.m[2] *= this._scalingDeterminant;
  61116. mat.getRotationMatrixToRef(result);
  61117. }
  61118. };
  61119. /**
  61120. * Get the world position of a point that is in the local space of the bone.
  61121. * @param position The local position
  61122. * @param mesh The mesh that this bone is attached to.
  61123. * @returns The world position
  61124. */
  61125. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  61126. if (mesh === void 0) { mesh = null; }
  61127. var result = BABYLON.Vector3.Zero();
  61128. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  61129. return result;
  61130. };
  61131. /**
  61132. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  61133. * @param position The local position
  61134. * @param mesh The mesh that this bone is attached to.
  61135. * @param result The vector3 that the world position should be copied to.
  61136. */
  61137. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  61138. if (mesh === void 0) { mesh = null; }
  61139. var wm = null;
  61140. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61141. if (mesh) {
  61142. wm = mesh.getWorldMatrix();
  61143. }
  61144. this._skeleton.computeAbsoluteTransforms();
  61145. var tmat = Bone._tmpMats[0];
  61146. if (mesh && wm) {
  61147. tmat.copyFrom(this.getAbsoluteTransform());
  61148. tmat.multiplyToRef(wm, tmat);
  61149. }
  61150. else {
  61151. tmat = this.getAbsoluteTransform();
  61152. }
  61153. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61154. };
  61155. /**
  61156. * Get the local position of a point that is in world space.
  61157. * @param position The world position
  61158. * @param mesh The mesh that this bone is attached to.
  61159. * @returns The local position
  61160. */
  61161. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  61162. if (mesh === void 0) { mesh = null; }
  61163. var result = BABYLON.Vector3.Zero();
  61164. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61165. return result;
  61166. };
  61167. /**
  61168. * Get the local position of a point that is in world space and copy it to the result param.
  61169. * @param position The world position
  61170. * @param mesh The mesh that this bone is attached to.
  61171. * @param result The vector3 that the local position should be copied to.
  61172. */
  61173. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61174. if (mesh === void 0) { mesh = null; }
  61175. var wm = null;
  61176. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61177. if (mesh) {
  61178. wm = mesh.getWorldMatrix();
  61179. }
  61180. this._skeleton.computeAbsoluteTransforms();
  61181. var tmat = Bone._tmpMats[0];
  61182. tmat.copyFrom(this.getAbsoluteTransform());
  61183. if (mesh && wm) {
  61184. tmat.multiplyToRef(wm, tmat);
  61185. }
  61186. tmat.invert();
  61187. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61188. };
  61189. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61190. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61191. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61192. return Bone;
  61193. }(BABYLON.Node));
  61194. BABYLON.Bone = Bone;
  61195. })(BABYLON || (BABYLON = {}));
  61196. //# sourceMappingURL=babylon.bone.js.map
  61197. var BABYLON;
  61198. (function (BABYLON) {
  61199. var BoneIKController = /** @class */ (function () {
  61200. function BoneIKController(mesh, bone, options) {
  61201. this.targetPosition = BABYLON.Vector3.Zero();
  61202. this.poleTargetPosition = BABYLON.Vector3.Zero();
  61203. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  61204. this.poleAngle = 0;
  61205. this.slerpAmount = 1;
  61206. this._bone1Quat = BABYLON.Quaternion.Identity();
  61207. this._bone1Mat = BABYLON.Matrix.Identity();
  61208. this._bone2Ang = Math.PI;
  61209. this._maxAngle = Math.PI;
  61210. this._rightHandedSystem = false;
  61211. this._bendAxis = BABYLON.Vector3.Right();
  61212. this._slerping = false;
  61213. this._adjustRoll = 0;
  61214. this._bone2 = bone;
  61215. this._bone1 = bone.getParent();
  61216. if (!this._bone1) {
  61217. return;
  61218. }
  61219. this.mesh = mesh;
  61220. var bonePos = bone.getPosition();
  61221. if (bone.getAbsoluteTransform().determinant() > 0) {
  61222. this._rightHandedSystem = true;
  61223. this._bendAxis.x = 0;
  61224. this._bendAxis.y = 0;
  61225. this._bendAxis.z = -1;
  61226. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  61227. this._adjustRoll = Math.PI * .5;
  61228. this._bendAxis.z = 1;
  61229. }
  61230. }
  61231. if (this._bone1.length) {
  61232. var boneScale1 = this._bone1.getScale();
  61233. var boneScale2 = this._bone2.getScale();
  61234. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  61235. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  61236. }
  61237. else if (this._bone1.children[0]) {
  61238. mesh.computeWorldMatrix(true);
  61239. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  61240. var pos2 = this._bone2.getAbsolutePosition(mesh);
  61241. var pos3 = this._bone1.getAbsolutePosition(mesh);
  61242. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  61243. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  61244. }
  61245. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  61246. this.maxAngle = Math.PI;
  61247. if (options) {
  61248. if (options.targetMesh) {
  61249. this.targetMesh = options.targetMesh;
  61250. this.targetMesh.computeWorldMatrix(true);
  61251. }
  61252. if (options.poleTargetMesh) {
  61253. this.poleTargetMesh = options.poleTargetMesh;
  61254. this.poleTargetMesh.computeWorldMatrix(true);
  61255. }
  61256. else if (options.poleTargetBone) {
  61257. this.poleTargetBone = options.poleTargetBone;
  61258. }
  61259. else if (this._bone1.getParent()) {
  61260. this.poleTargetBone = this._bone1.getParent();
  61261. }
  61262. if (options.poleTargetLocalOffset) {
  61263. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  61264. }
  61265. if (options.poleAngle) {
  61266. this.poleAngle = options.poleAngle;
  61267. }
  61268. if (options.bendAxis) {
  61269. this._bendAxis.copyFrom(options.bendAxis);
  61270. }
  61271. if (options.maxAngle) {
  61272. this.maxAngle = options.maxAngle;
  61273. }
  61274. if (options.slerpAmount) {
  61275. this.slerpAmount = options.slerpAmount;
  61276. }
  61277. }
  61278. }
  61279. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  61280. get: function () {
  61281. return this._maxAngle;
  61282. },
  61283. set: function (value) {
  61284. this._setMaxAngle(value);
  61285. },
  61286. enumerable: true,
  61287. configurable: true
  61288. });
  61289. BoneIKController.prototype._setMaxAngle = function (ang) {
  61290. if (ang < 0) {
  61291. ang = 0;
  61292. }
  61293. if (ang > Math.PI || ang == undefined) {
  61294. ang = Math.PI;
  61295. }
  61296. this._maxAngle = ang;
  61297. var a = this._bone1Length;
  61298. var b = this._bone2Length;
  61299. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  61300. };
  61301. BoneIKController.prototype.update = function () {
  61302. var bone1 = this._bone1;
  61303. if (!bone1) {
  61304. return;
  61305. }
  61306. var target = this.targetPosition;
  61307. var poleTarget = this.poleTargetPosition;
  61308. var mat1 = BoneIKController._tmpMats[0];
  61309. var mat2 = BoneIKController._tmpMats[1];
  61310. if (this.targetMesh) {
  61311. target.copyFrom(this.targetMesh.getAbsolutePosition());
  61312. }
  61313. if (this.poleTargetBone) {
  61314. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  61315. }
  61316. else if (this.poleTargetMesh) {
  61317. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  61318. }
  61319. var bonePos = BoneIKController._tmpVecs[0];
  61320. var zaxis = BoneIKController._tmpVecs[1];
  61321. var xaxis = BoneIKController._tmpVecs[2];
  61322. var yaxis = BoneIKController._tmpVecs[3];
  61323. var upAxis = BoneIKController._tmpVecs[4];
  61324. var _tmpQuat = BoneIKController._tmpQuat;
  61325. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  61326. poleTarget.subtractToRef(bonePos, upAxis);
  61327. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  61328. upAxis.y = 1;
  61329. }
  61330. else {
  61331. upAxis.normalize();
  61332. }
  61333. target.subtractToRef(bonePos, yaxis);
  61334. yaxis.normalize();
  61335. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  61336. zaxis.normalize();
  61337. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  61338. xaxis.normalize();
  61339. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  61340. var a = this._bone1Length;
  61341. var b = this._bone2Length;
  61342. var c = BABYLON.Vector3.Distance(bonePos, target);
  61343. if (this._maxReach > 0) {
  61344. c = Math.min(this._maxReach, c);
  61345. }
  61346. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  61347. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  61348. if (acosa > 1) {
  61349. acosa = 1;
  61350. }
  61351. if (acosb > 1) {
  61352. acosb = 1;
  61353. }
  61354. if (acosa < -1) {
  61355. acosa = -1;
  61356. }
  61357. if (acosb < -1) {
  61358. acosb = -1;
  61359. }
  61360. var angA = Math.acos(acosa);
  61361. var angB = Math.acos(acosb);
  61362. var angC = -angA - angB;
  61363. if (this._rightHandedSystem) {
  61364. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  61365. mat2.multiplyToRef(mat1, mat1);
  61366. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  61367. mat2.multiplyToRef(mat1, mat1);
  61368. }
  61369. else {
  61370. var _tmpVec = BoneIKController._tmpVecs[5];
  61371. _tmpVec.copyFrom(this._bendAxis);
  61372. _tmpVec.x *= -1;
  61373. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  61374. mat2.multiplyToRef(mat1, mat1);
  61375. }
  61376. if (this.poleAngle) {
  61377. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  61378. mat1.multiplyToRef(mat2, mat1);
  61379. }
  61380. if (this._bone1) {
  61381. if (this.slerpAmount < 1) {
  61382. if (!this._slerping) {
  61383. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  61384. }
  61385. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  61386. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  61387. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  61388. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  61389. this._slerping = true;
  61390. }
  61391. else {
  61392. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  61393. this._bone1Mat.copyFrom(mat1);
  61394. this._slerping = false;
  61395. }
  61396. }
  61397. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  61398. this._bone2Ang = angC;
  61399. };
  61400. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61401. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  61402. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61403. return BoneIKController;
  61404. }());
  61405. BABYLON.BoneIKController = BoneIKController;
  61406. })(BABYLON || (BABYLON = {}));
  61407. //# sourceMappingURL=babylon.boneIKController.js.map
  61408. var BABYLON;
  61409. (function (BABYLON) {
  61410. var BoneLookController = /** @class */ (function () {
  61411. /**
  61412. * Create a BoneLookController
  61413. * @param mesh the mesh that the bone belongs to
  61414. * @param bone the bone that will be looking to the target
  61415. * @param target the target Vector3 to look at
  61416. * @param settings optional settings:
  61417. * - maxYaw: the maximum angle the bone will yaw to
  61418. * - minYaw: the minimum angle the bone will yaw to
  61419. * - maxPitch: the maximum angle the bone will pitch to
  61420. * - minPitch: the minimum angle the bone will yaw to
  61421. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  61422. * - upAxis: the up axis of the coordinate system
  61423. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61424. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  61425. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  61426. * - adjustYaw: used to make an adjustment to the yaw of the bone
  61427. * - adjustPitch: used to make an adjustment to the pitch of the bone
  61428. * - adjustRoll: used to make an adjustment to the roll of the bone
  61429. **/
  61430. function BoneLookController(mesh, bone, target, options) {
  61431. /**
  61432. * The up axis of the coordinate system that is used when the bone is rotated.
  61433. */
  61434. this.upAxis = BABYLON.Vector3.Up();
  61435. /**
  61436. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61437. */
  61438. this.upAxisSpace = BABYLON.Space.LOCAL;
  61439. /**
  61440. * Used to make an adjustment to the yaw of the bone.
  61441. */
  61442. this.adjustYaw = 0;
  61443. /**
  61444. * Used to make an adjustment to the pitch of the bone.
  61445. */
  61446. this.adjustPitch = 0;
  61447. /**
  61448. * Used to make an adjustment to the roll of the bone.
  61449. */
  61450. this.adjustRoll = 0;
  61451. /**
  61452. * 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).
  61453. */
  61454. this.slerpAmount = 1;
  61455. this._boneQuat = BABYLON.Quaternion.Identity();
  61456. this._slerping = false;
  61457. this._firstFrameSkipped = false;
  61458. this._fowardAxis = BABYLON.Vector3.Forward();
  61459. this.mesh = mesh;
  61460. this.bone = bone;
  61461. this.target = target;
  61462. if (options) {
  61463. if (options.adjustYaw) {
  61464. this.adjustYaw = options.adjustYaw;
  61465. }
  61466. if (options.adjustPitch) {
  61467. this.adjustPitch = options.adjustPitch;
  61468. }
  61469. if (options.adjustRoll) {
  61470. this.adjustRoll = options.adjustRoll;
  61471. }
  61472. if (options.maxYaw != null) {
  61473. this.maxYaw = options.maxYaw;
  61474. }
  61475. else {
  61476. this.maxYaw = Math.PI;
  61477. }
  61478. if (options.minYaw != null) {
  61479. this.minYaw = options.minYaw;
  61480. }
  61481. else {
  61482. this.minYaw = -Math.PI;
  61483. }
  61484. if (options.maxPitch != null) {
  61485. this.maxPitch = options.maxPitch;
  61486. }
  61487. else {
  61488. this.maxPitch = Math.PI;
  61489. }
  61490. if (options.minPitch != null) {
  61491. this.minPitch = options.minPitch;
  61492. }
  61493. else {
  61494. this.minPitch = -Math.PI;
  61495. }
  61496. if (options.slerpAmount != null) {
  61497. this.slerpAmount = options.slerpAmount;
  61498. }
  61499. if (options.upAxis != null) {
  61500. this.upAxis = options.upAxis;
  61501. }
  61502. if (options.upAxisSpace != null) {
  61503. this.upAxisSpace = options.upAxisSpace;
  61504. }
  61505. if (options.yawAxis != null || options.pitchAxis != null) {
  61506. var newYawAxis = BABYLON.Axis.Y;
  61507. var newPitchAxis = BABYLON.Axis.X;
  61508. if (options.yawAxis != null) {
  61509. newYawAxis = options.yawAxis.clone();
  61510. newYawAxis.normalize();
  61511. }
  61512. if (options.pitchAxis != null) {
  61513. newPitchAxis = options.pitchAxis.clone();
  61514. newPitchAxis.normalize();
  61515. }
  61516. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  61517. this._transformYawPitch = BABYLON.Matrix.Identity();
  61518. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  61519. this._transformYawPitchInv = this._transformYawPitch.clone();
  61520. this._transformYawPitch.invert();
  61521. }
  61522. }
  61523. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  61524. this.upAxisSpace = BABYLON.Space.LOCAL;
  61525. }
  61526. }
  61527. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  61528. /**
  61529. * Get/set the minimum yaw angle that the bone can look to.
  61530. */
  61531. get: function () {
  61532. return this._minYaw;
  61533. },
  61534. set: function (value) {
  61535. this._minYaw = value;
  61536. this._minYawSin = Math.sin(value);
  61537. this._minYawCos = Math.cos(value);
  61538. if (this._maxYaw != null) {
  61539. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61540. this._yawRange = this._maxYaw - this._minYaw;
  61541. }
  61542. },
  61543. enumerable: true,
  61544. configurable: true
  61545. });
  61546. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  61547. /**
  61548. * Get/set the maximum yaw angle that the bone can look to.
  61549. */
  61550. get: function () {
  61551. return this._maxYaw;
  61552. },
  61553. set: function (value) {
  61554. this._maxYaw = value;
  61555. this._maxYawSin = Math.sin(value);
  61556. this._maxYawCos = Math.cos(value);
  61557. if (this._minYaw != null) {
  61558. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61559. this._yawRange = this._maxYaw - this._minYaw;
  61560. }
  61561. },
  61562. enumerable: true,
  61563. configurable: true
  61564. });
  61565. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  61566. /**
  61567. * Get/set the minimum pitch angle that the bone can look to.
  61568. */
  61569. get: function () {
  61570. return this._minPitch;
  61571. },
  61572. set: function (value) {
  61573. this._minPitch = value;
  61574. this._minPitchTan = Math.tan(value);
  61575. },
  61576. enumerable: true,
  61577. configurable: true
  61578. });
  61579. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  61580. /**
  61581. * Get/set the maximum pitch angle that the bone can look to.
  61582. */
  61583. get: function () {
  61584. return this._maxPitch;
  61585. },
  61586. set: function (value) {
  61587. this._maxPitch = value;
  61588. this._maxPitchTan = Math.tan(value);
  61589. },
  61590. enumerable: true,
  61591. configurable: true
  61592. });
  61593. /**
  61594. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  61595. */
  61596. BoneLookController.prototype.update = function () {
  61597. //skip the first frame when slerping so that the mesh rotation is correct
  61598. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  61599. this._firstFrameSkipped = true;
  61600. return;
  61601. }
  61602. var bone = this.bone;
  61603. var bonePos = BoneLookController._tmpVecs[0];
  61604. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  61605. var target = this.target;
  61606. var _tmpMat1 = BoneLookController._tmpMats[0];
  61607. var _tmpMat2 = BoneLookController._tmpMats[1];
  61608. var mesh = this.mesh;
  61609. var parentBone = bone.getParent();
  61610. var upAxis = BoneLookController._tmpVecs[1];
  61611. upAxis.copyFrom(this.upAxis);
  61612. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  61613. if (this._transformYawPitch) {
  61614. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  61615. }
  61616. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  61617. }
  61618. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  61619. mesh.getDirectionToRef(upAxis, upAxis);
  61620. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  61621. upAxis.normalize();
  61622. }
  61623. }
  61624. var checkYaw = false;
  61625. var checkPitch = false;
  61626. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  61627. checkYaw = true;
  61628. }
  61629. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  61630. checkPitch = true;
  61631. }
  61632. if (checkYaw || checkPitch) {
  61633. var spaceMat = BoneLookController._tmpMats[2];
  61634. var spaceMatInv = BoneLookController._tmpMats[3];
  61635. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  61636. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  61637. }
  61638. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  61639. spaceMat.copyFrom(mesh.getWorldMatrix());
  61640. }
  61641. else {
  61642. var forwardAxis = BoneLookController._tmpVecs[2];
  61643. forwardAxis.copyFrom(this._fowardAxis);
  61644. if (this._transformYawPitch) {
  61645. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  61646. }
  61647. if (parentBone) {
  61648. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  61649. }
  61650. else {
  61651. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  61652. }
  61653. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  61654. rightAxis.normalize();
  61655. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  61656. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  61657. }
  61658. spaceMat.invertToRef(spaceMatInv);
  61659. var xzlen = null;
  61660. if (checkPitch) {
  61661. var localTarget = BoneLookController._tmpVecs[3];
  61662. target.subtractToRef(bonePos, localTarget);
  61663. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61664. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61665. var pitch = Math.atan2(localTarget.y, xzlen);
  61666. var newPitch = pitch;
  61667. if (pitch > this._maxPitch) {
  61668. localTarget.y = this._maxPitchTan * xzlen;
  61669. newPitch = this._maxPitch;
  61670. }
  61671. else if (pitch < this._minPitch) {
  61672. localTarget.y = this._minPitchTan * xzlen;
  61673. newPitch = this._minPitch;
  61674. }
  61675. if (pitch != newPitch) {
  61676. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61677. localTarget.addInPlace(bonePos);
  61678. target = localTarget;
  61679. }
  61680. }
  61681. if (checkYaw) {
  61682. var localTarget = BoneLookController._tmpVecs[4];
  61683. target.subtractToRef(bonePos, localTarget);
  61684. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61685. var yaw = Math.atan2(localTarget.x, localTarget.z);
  61686. var newYaw = yaw;
  61687. if (yaw > this._maxYaw || yaw < this._minYaw) {
  61688. if (xzlen == null) {
  61689. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61690. }
  61691. if (this._yawRange > Math.PI) {
  61692. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  61693. localTarget.z = this._maxYawCos * xzlen;
  61694. localTarget.x = this._maxYawSin * xzlen;
  61695. newYaw = this._maxYaw;
  61696. }
  61697. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  61698. localTarget.z = this._minYawCos * xzlen;
  61699. localTarget.x = this._minYawSin * xzlen;
  61700. newYaw = this._minYaw;
  61701. }
  61702. }
  61703. else {
  61704. if (yaw > this._maxYaw) {
  61705. localTarget.z = this._maxYawCos * xzlen;
  61706. localTarget.x = this._maxYawSin * xzlen;
  61707. newYaw = this._maxYaw;
  61708. }
  61709. else if (yaw < this._minYaw) {
  61710. localTarget.z = this._minYawCos * xzlen;
  61711. localTarget.x = this._minYawSin * xzlen;
  61712. newYaw = this._minYaw;
  61713. }
  61714. }
  61715. }
  61716. if (this._slerping && this._yawRange > Math.PI) {
  61717. //are we going to be crossing into the min/max region?
  61718. var boneFwd = BoneLookController._tmpVecs[8];
  61719. boneFwd.copyFrom(BABYLON.Axis.Z);
  61720. if (this._transformYawPitch) {
  61721. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  61722. }
  61723. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  61724. this._boneQuat.toRotationMatrix(boneRotMat);
  61725. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  61726. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  61727. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  61728. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  61729. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  61730. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  61731. if (angBtwTar > angBtwMidYaw) {
  61732. if (xzlen == null) {
  61733. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61734. }
  61735. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  61736. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  61737. if (angBtwMin < angBtwMax) {
  61738. newYaw = boneYaw + Math.PI * .75;
  61739. localTarget.z = Math.cos(newYaw) * xzlen;
  61740. localTarget.x = Math.sin(newYaw) * xzlen;
  61741. }
  61742. else {
  61743. newYaw = boneYaw - Math.PI * .75;
  61744. localTarget.z = Math.cos(newYaw) * xzlen;
  61745. localTarget.x = Math.sin(newYaw) * xzlen;
  61746. }
  61747. }
  61748. }
  61749. if (yaw != newYaw) {
  61750. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61751. localTarget.addInPlace(bonePos);
  61752. target = localTarget;
  61753. }
  61754. }
  61755. }
  61756. var zaxis = BoneLookController._tmpVecs[5];
  61757. var xaxis = BoneLookController._tmpVecs[6];
  61758. var yaxis = BoneLookController._tmpVecs[7];
  61759. var _tmpQuat = BoneLookController._tmpQuat;
  61760. target.subtractToRef(bonePos, zaxis);
  61761. zaxis.normalize();
  61762. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  61763. xaxis.normalize();
  61764. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  61765. yaxis.normalize();
  61766. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  61767. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  61768. return;
  61769. }
  61770. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  61771. return;
  61772. }
  61773. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  61774. return;
  61775. }
  61776. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  61777. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  61778. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  61779. }
  61780. if (this.slerpAmount < 1) {
  61781. if (!this._slerping) {
  61782. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  61783. }
  61784. if (this._transformYawPitch) {
  61785. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61786. }
  61787. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  61788. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  61789. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  61790. this._slerping = true;
  61791. }
  61792. else {
  61793. if (this._transformYawPitch) {
  61794. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61795. }
  61796. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  61797. this._slerping = false;
  61798. }
  61799. };
  61800. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  61801. var angDiff = ang2 - ang1;
  61802. angDiff %= Math.PI * 2;
  61803. if (angDiff > Math.PI) {
  61804. angDiff -= Math.PI * 2;
  61805. }
  61806. else if (angDiff < -Math.PI) {
  61807. angDiff += Math.PI * 2;
  61808. }
  61809. return angDiff;
  61810. };
  61811. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  61812. ang1 %= (2 * Math.PI);
  61813. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61814. ang2 %= (2 * Math.PI);
  61815. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61816. var ab = 0;
  61817. if (ang1 < ang2) {
  61818. ab = ang2 - ang1;
  61819. }
  61820. else {
  61821. ab = ang1 - ang2;
  61822. }
  61823. if (ab > Math.PI) {
  61824. ab = Math.PI * 2 - ab;
  61825. }
  61826. return ab;
  61827. };
  61828. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  61829. ang %= (2 * Math.PI);
  61830. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  61831. ang1 %= (2 * Math.PI);
  61832. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61833. ang2 %= (2 * Math.PI);
  61834. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61835. if (ang1 < ang2) {
  61836. if (ang > ang1 && ang < ang2) {
  61837. return true;
  61838. }
  61839. }
  61840. else {
  61841. if (ang > ang2 && ang < ang1) {
  61842. return true;
  61843. }
  61844. }
  61845. return false;
  61846. };
  61847. 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()];
  61848. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  61849. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61850. return BoneLookController;
  61851. }());
  61852. BABYLON.BoneLookController = BoneLookController;
  61853. })(BABYLON || (BABYLON = {}));
  61854. //# sourceMappingURL=babylon.boneLookController.js.map
  61855. var BABYLON;
  61856. (function (BABYLON) {
  61857. var Skeleton = /** @class */ (function () {
  61858. function Skeleton(name, id, scene) {
  61859. this.name = name;
  61860. this.id = id;
  61861. this.bones = new Array();
  61862. this.needInitialSkinMatrix = false;
  61863. this._isDirty = true;
  61864. this._meshesWithPoseMatrix = new Array();
  61865. this._identity = BABYLON.Matrix.Identity();
  61866. this._ranges = {};
  61867. this._lastAbsoluteTransformsUpdateId = -1;
  61868. // Events
  61869. /**
  61870. * An event triggered before computing the skeleton's matrices
  61871. * @type {BABYLON.Observable}
  61872. */
  61873. this.onBeforeComputeObservable = new BABYLON.Observable();
  61874. this.bones = [];
  61875. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61876. scene.skeletons.push(this);
  61877. //make sure it will recalculate the matrix next time prepare is called.
  61878. this._isDirty = true;
  61879. }
  61880. // Members
  61881. Skeleton.prototype.getTransformMatrices = function (mesh) {
  61882. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  61883. return mesh._bonesTransformMatrices;
  61884. }
  61885. if (!this._transformMatrices) {
  61886. this.prepare();
  61887. }
  61888. return this._transformMatrices;
  61889. };
  61890. Skeleton.prototype.getScene = function () {
  61891. return this._scene;
  61892. };
  61893. // Methods
  61894. /**
  61895. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  61896. */
  61897. Skeleton.prototype.toString = function (fullDetails) {
  61898. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  61899. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  61900. if (fullDetails) {
  61901. ret += ", Ranges: {";
  61902. var first = true;
  61903. for (var name_1 in this._ranges) {
  61904. if (first) {
  61905. ret += ", ";
  61906. first = false;
  61907. }
  61908. ret += name_1;
  61909. }
  61910. ret += "}";
  61911. }
  61912. return ret;
  61913. };
  61914. /**
  61915. * Get bone's index searching by name
  61916. * @param {string} name is bone's name to search for
  61917. * @return {number} Indice of the bone. Returns -1 if not found
  61918. */
  61919. Skeleton.prototype.getBoneIndexByName = function (name) {
  61920. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  61921. if (this.bones[boneIndex].name === name) {
  61922. return boneIndex;
  61923. }
  61924. }
  61925. return -1;
  61926. };
  61927. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  61928. // check name not already in use
  61929. if (!this._ranges[name]) {
  61930. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  61931. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61932. if (this.bones[i].animations[0]) {
  61933. this.bones[i].animations[0].createRange(name, from, to);
  61934. }
  61935. }
  61936. }
  61937. };
  61938. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  61939. if (deleteFrames === void 0) { deleteFrames = true; }
  61940. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61941. if (this.bones[i].animations[0]) {
  61942. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  61943. }
  61944. }
  61945. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  61946. };
  61947. Skeleton.prototype.getAnimationRange = function (name) {
  61948. return this._ranges[name];
  61949. };
  61950. /**
  61951. * Returns as an Array, all AnimationRanges defined on this skeleton
  61952. */
  61953. Skeleton.prototype.getAnimationRanges = function () {
  61954. var animationRanges = [];
  61955. var name;
  61956. var i = 0;
  61957. for (name in this._ranges) {
  61958. animationRanges[i] = this._ranges[name];
  61959. i++;
  61960. }
  61961. return animationRanges;
  61962. };
  61963. /**
  61964. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  61965. */
  61966. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  61967. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61968. if (this._ranges[name] || !source.getAnimationRange(name)) {
  61969. return false;
  61970. }
  61971. var ret = true;
  61972. var frameOffset = this._getHighestAnimationFrame() + 1;
  61973. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  61974. var boneDict = {};
  61975. var sourceBones = source.bones;
  61976. var nBones;
  61977. var i;
  61978. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  61979. boneDict[sourceBones[i].name] = sourceBones[i];
  61980. }
  61981. if (this.bones.length !== sourceBones.length) {
  61982. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  61983. ret = false;
  61984. }
  61985. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  61986. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  61987. var boneName = this.bones[i].name;
  61988. var sourceBone = boneDict[boneName];
  61989. if (sourceBone) {
  61990. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  61991. }
  61992. else {
  61993. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  61994. ret = false;
  61995. }
  61996. }
  61997. // do not call createAnimationRange(), since it also is done to bones, which was already done
  61998. var range = source.getAnimationRange(name);
  61999. if (range) {
  62000. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  62001. }
  62002. return ret;
  62003. };
  62004. Skeleton.prototype.returnToRest = function () {
  62005. for (var index = 0; index < this.bones.length; index++) {
  62006. this.bones[index].returnToRest();
  62007. }
  62008. };
  62009. Skeleton.prototype._getHighestAnimationFrame = function () {
  62010. var ret = 0;
  62011. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62012. if (this.bones[i].animations[0]) {
  62013. var highest = this.bones[i].animations[0].getHighestFrame();
  62014. if (ret < highest) {
  62015. ret = highest;
  62016. }
  62017. }
  62018. }
  62019. return ret;
  62020. };
  62021. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  62022. var range = this.getAnimationRange(name);
  62023. if (!range) {
  62024. return null;
  62025. }
  62026. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  62027. };
  62028. Skeleton.prototype._markAsDirty = function () {
  62029. this._isDirty = true;
  62030. };
  62031. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  62032. this._meshesWithPoseMatrix.push(mesh);
  62033. };
  62034. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  62035. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  62036. if (index > -1) {
  62037. this._meshesWithPoseMatrix.splice(index, 1);
  62038. }
  62039. };
  62040. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  62041. this.onBeforeComputeObservable.notifyObservers(this);
  62042. for (var index = 0; index < this.bones.length; index++) {
  62043. var bone = this.bones[index];
  62044. var parentBone = bone.getParent();
  62045. if (parentBone) {
  62046. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  62047. }
  62048. else {
  62049. if (initialSkinMatrix) {
  62050. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  62051. }
  62052. else {
  62053. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  62054. }
  62055. }
  62056. if (bone._index !== -1) {
  62057. var mappedIndex = bone._index === null ? index : bone._index;
  62058. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  62059. }
  62060. }
  62061. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  62062. };
  62063. Skeleton.prototype.prepare = function () {
  62064. if (!this._isDirty) {
  62065. return;
  62066. }
  62067. if (this.needInitialSkinMatrix) {
  62068. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  62069. var mesh = this._meshesWithPoseMatrix[index];
  62070. var poseMatrix = mesh.getPoseMatrix();
  62071. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  62072. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62073. }
  62074. if (this._synchronizedWithMesh !== mesh) {
  62075. this._synchronizedWithMesh = mesh;
  62076. // Prepare bones
  62077. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  62078. var bone = this.bones[boneIndex];
  62079. if (!bone.getParent()) {
  62080. var matrix = bone.getBaseMatrix();
  62081. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  62082. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  62083. }
  62084. }
  62085. }
  62086. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  62087. }
  62088. }
  62089. else {
  62090. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  62091. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62092. }
  62093. this._computeTransformMatrices(this._transformMatrices, null);
  62094. }
  62095. this._isDirty = false;
  62096. this._scene._activeBones.addCount(this.bones.length, false);
  62097. };
  62098. Skeleton.prototype.getAnimatables = function () {
  62099. if (!this._animatables || this._animatables.length !== this.bones.length) {
  62100. this._animatables = [];
  62101. for (var index = 0; index < this.bones.length; index++) {
  62102. this._animatables.push(this.bones[index]);
  62103. }
  62104. }
  62105. return this._animatables;
  62106. };
  62107. Skeleton.prototype.clone = function (name, id) {
  62108. var result = new Skeleton(name, id || name, this._scene);
  62109. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62110. for (var index = 0; index < this.bones.length; index++) {
  62111. var source = this.bones[index];
  62112. var parentBone = null;
  62113. var parent_1 = source.getParent();
  62114. if (parent_1) {
  62115. var parentIndex = this.bones.indexOf(parent_1);
  62116. parentBone = result.bones[parentIndex];
  62117. }
  62118. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  62119. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  62120. }
  62121. if (this._ranges) {
  62122. result._ranges = {};
  62123. for (var rangeName in this._ranges) {
  62124. var range = this._ranges[rangeName];
  62125. if (range) {
  62126. result._ranges[rangeName] = range.clone();
  62127. }
  62128. }
  62129. }
  62130. this._isDirty = true;
  62131. return result;
  62132. };
  62133. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  62134. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  62135. this.bones.forEach(function (bone) {
  62136. bone.animations.forEach(function (animation) {
  62137. animation.enableBlending = true;
  62138. animation.blendingSpeed = blendingSpeed;
  62139. });
  62140. });
  62141. };
  62142. Skeleton.prototype.dispose = function () {
  62143. this._meshesWithPoseMatrix = [];
  62144. // Animations
  62145. this.getScene().stopAnimation(this);
  62146. // Remove from scene
  62147. this.getScene().removeSkeleton(this);
  62148. };
  62149. Skeleton.prototype.serialize = function () {
  62150. var serializationObject = {};
  62151. serializationObject.name = this.name;
  62152. serializationObject.id = this.id;
  62153. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  62154. serializationObject.bones = [];
  62155. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62156. for (var index = 0; index < this.bones.length; index++) {
  62157. var bone = this.bones[index];
  62158. var parent_2 = bone.getParent();
  62159. var serializedBone = {
  62160. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  62161. name: bone.name,
  62162. matrix: bone.getBaseMatrix().toArray(),
  62163. rest: bone.getRestPose().toArray()
  62164. };
  62165. serializationObject.bones.push(serializedBone);
  62166. if (bone.length) {
  62167. serializedBone.length = bone.length;
  62168. }
  62169. if (bone.animations && bone.animations.length > 0) {
  62170. serializedBone.animation = bone.animations[0].serialize();
  62171. }
  62172. serializationObject.ranges = [];
  62173. for (var name in this._ranges) {
  62174. var source = this._ranges[name];
  62175. if (!source) {
  62176. continue;
  62177. }
  62178. var range = {};
  62179. range.name = name;
  62180. range.from = source.from;
  62181. range.to = source.to;
  62182. serializationObject.ranges.push(range);
  62183. }
  62184. }
  62185. return serializationObject;
  62186. };
  62187. Skeleton.Parse = function (parsedSkeleton, scene) {
  62188. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62189. if (parsedSkeleton.dimensionsAtRest) {
  62190. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62191. }
  62192. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  62193. var index;
  62194. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  62195. var parsedBone = parsedSkeleton.bones[index];
  62196. var parentBone = null;
  62197. if (parsedBone.parentBoneIndex > -1) {
  62198. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  62199. }
  62200. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  62201. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  62202. if (parsedBone.length) {
  62203. bone.length = parsedBone.length;
  62204. }
  62205. if (parsedBone.animation) {
  62206. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  62207. }
  62208. }
  62209. // placed after bones, so createAnimationRange can cascade down
  62210. if (parsedSkeleton.ranges) {
  62211. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  62212. var data = parsedSkeleton.ranges[index];
  62213. skeleton.createAnimationRange(data.name, data.from, data.to);
  62214. }
  62215. }
  62216. return skeleton;
  62217. };
  62218. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  62219. if (forceUpdate === void 0) { forceUpdate = false; }
  62220. var renderId = this._scene.getRenderId();
  62221. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  62222. this.bones[0].computeAbsoluteTransforms();
  62223. this._lastAbsoluteTransformsUpdateId = renderId;
  62224. }
  62225. };
  62226. Skeleton.prototype.getPoseMatrix = function () {
  62227. var poseMatrix = null;
  62228. if (this._meshesWithPoseMatrix.length > 0) {
  62229. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  62230. }
  62231. return poseMatrix;
  62232. };
  62233. Skeleton.prototype.sortBones = function () {
  62234. var bones = new Array();
  62235. var visited = new Array(this.bones.length);
  62236. for (var index = 0; index < this.bones.length; index++) {
  62237. this._sortBones(index, bones, visited);
  62238. }
  62239. this.bones = bones;
  62240. };
  62241. Skeleton.prototype._sortBones = function (index, bones, visited) {
  62242. if (visited[index]) {
  62243. return;
  62244. }
  62245. visited[index] = true;
  62246. var bone = this.bones[index];
  62247. if (bone._index === undefined) {
  62248. bone._index = index;
  62249. }
  62250. var parentBone = bone.getParent();
  62251. if (parentBone) {
  62252. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  62253. }
  62254. bones.push(bone);
  62255. };
  62256. return Skeleton;
  62257. }());
  62258. BABYLON.Skeleton = Skeleton;
  62259. })(BABYLON || (BABYLON = {}));
  62260. //# sourceMappingURL=babylon.skeleton.js.map
  62261. var BABYLON;
  62262. (function (BABYLON) {
  62263. var SphericalPolynomial = /** @class */ (function () {
  62264. function SphericalPolynomial() {
  62265. this.x = BABYLON.Vector3.Zero();
  62266. this.y = BABYLON.Vector3.Zero();
  62267. this.z = BABYLON.Vector3.Zero();
  62268. this.xx = BABYLON.Vector3.Zero();
  62269. this.yy = BABYLON.Vector3.Zero();
  62270. this.zz = BABYLON.Vector3.Zero();
  62271. this.xy = BABYLON.Vector3.Zero();
  62272. this.yz = BABYLON.Vector3.Zero();
  62273. this.zx = BABYLON.Vector3.Zero();
  62274. }
  62275. SphericalPolynomial.prototype.addAmbient = function (color) {
  62276. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62277. this.xx = this.xx.add(colorVector);
  62278. this.yy = this.yy.add(colorVector);
  62279. this.zz = this.zz.add(colorVector);
  62280. };
  62281. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  62282. var result = new SphericalPolynomial();
  62283. result.x = harmonics.L11.scale(1.02333);
  62284. result.y = harmonics.L1_1.scale(1.02333);
  62285. result.z = harmonics.L10.scale(1.02333);
  62286. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  62287. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  62288. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  62289. result.yz = harmonics.L2_1.scale(0.858086);
  62290. result.zx = harmonics.L21.scale(0.858086);
  62291. result.xy = harmonics.L2_2.scale(0.858086);
  62292. result.scale(1.0 / Math.PI);
  62293. return result;
  62294. };
  62295. SphericalPolynomial.prototype.scale = function (scale) {
  62296. this.x = this.x.scale(scale);
  62297. this.y = this.y.scale(scale);
  62298. this.z = this.z.scale(scale);
  62299. this.xx = this.xx.scale(scale);
  62300. this.yy = this.yy.scale(scale);
  62301. this.zz = this.zz.scale(scale);
  62302. this.yz = this.yz.scale(scale);
  62303. this.zx = this.zx.scale(scale);
  62304. this.xy = this.xy.scale(scale);
  62305. };
  62306. return SphericalPolynomial;
  62307. }());
  62308. BABYLON.SphericalPolynomial = SphericalPolynomial;
  62309. var SphericalHarmonics = /** @class */ (function () {
  62310. function SphericalHarmonics() {
  62311. this.L00 = BABYLON.Vector3.Zero();
  62312. this.L1_1 = BABYLON.Vector3.Zero();
  62313. this.L10 = BABYLON.Vector3.Zero();
  62314. this.L11 = BABYLON.Vector3.Zero();
  62315. this.L2_2 = BABYLON.Vector3.Zero();
  62316. this.L2_1 = BABYLON.Vector3.Zero();
  62317. this.L20 = BABYLON.Vector3.Zero();
  62318. this.L21 = BABYLON.Vector3.Zero();
  62319. this.L22 = BABYLON.Vector3.Zero();
  62320. }
  62321. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  62322. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62323. var c = colorVector.scale(deltaSolidAngle);
  62324. this.L00 = this.L00.add(c.scale(0.282095));
  62325. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  62326. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  62327. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  62328. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  62329. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  62330. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  62331. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  62332. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  62333. };
  62334. SphericalHarmonics.prototype.scale = function (scale) {
  62335. this.L00 = this.L00.scale(scale);
  62336. this.L1_1 = this.L1_1.scale(scale);
  62337. this.L10 = this.L10.scale(scale);
  62338. this.L11 = this.L11.scale(scale);
  62339. this.L2_2 = this.L2_2.scale(scale);
  62340. this.L2_1 = this.L2_1.scale(scale);
  62341. this.L20 = this.L20.scale(scale);
  62342. this.L21 = this.L21.scale(scale);
  62343. this.L22 = this.L22.scale(scale);
  62344. };
  62345. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  62346. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  62347. //
  62348. // E_lm = A_l * L_lm
  62349. //
  62350. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  62351. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  62352. // the scaling factors are given in equation 9.
  62353. // Constant (Band 0)
  62354. this.L00 = this.L00.scale(3.141593);
  62355. // Linear (Band 1)
  62356. this.L1_1 = this.L1_1.scale(2.094395);
  62357. this.L10 = this.L10.scale(2.094395);
  62358. this.L11 = this.L11.scale(2.094395);
  62359. // Quadratic (Band 2)
  62360. this.L2_2 = this.L2_2.scale(0.785398);
  62361. this.L2_1 = this.L2_1.scale(0.785398);
  62362. this.L20 = this.L20.scale(0.785398);
  62363. this.L21 = this.L21.scale(0.785398);
  62364. this.L22 = this.L22.scale(0.785398);
  62365. };
  62366. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  62367. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  62368. // L = (1/pi) * E * rho
  62369. //
  62370. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  62371. this.scale(1.0 / Math.PI);
  62372. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  62373. // (The pixel shader must apply albedo after texture fetches, etc).
  62374. };
  62375. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  62376. var result = new SphericalHarmonics();
  62377. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  62378. result.L1_1 = polynomial.y.scale(0.977204);
  62379. result.L10 = polynomial.z.scale(0.977204);
  62380. result.L11 = polynomial.x.scale(0.977204);
  62381. result.L2_2 = polynomial.xy.scale(1.16538);
  62382. result.L2_1 = polynomial.yz.scale(1.16538);
  62383. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  62384. result.L21 = polynomial.zx.scale(1.16538);
  62385. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  62386. result.scale(Math.PI);
  62387. return result;
  62388. };
  62389. return SphericalHarmonics;
  62390. }());
  62391. BABYLON.SphericalHarmonics = SphericalHarmonics;
  62392. })(BABYLON || (BABYLON = {}));
  62393. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  62394. var BABYLON;
  62395. (function (BABYLON) {
  62396. var Internals;
  62397. (function (Internals) {
  62398. var FileFaceOrientation = /** @class */ (function () {
  62399. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  62400. this.name = name;
  62401. this.worldAxisForNormal = worldAxisForNormal;
  62402. this.worldAxisForFileX = worldAxisForFileX;
  62403. this.worldAxisForFileY = worldAxisForFileY;
  62404. }
  62405. return FileFaceOrientation;
  62406. }());
  62407. ;
  62408. /**
  62409. * Helper class dealing with the extraction of spherical polynomial dataArray
  62410. * from a cube map.
  62411. */
  62412. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  62413. function CubeMapToSphericalPolynomialTools() {
  62414. }
  62415. /**
  62416. * Converts a texture to the according Spherical Polynomial data.
  62417. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62418. *
  62419. * @param texture The texture to extract the information from.
  62420. * @return The Spherical Polynomial data.
  62421. */
  62422. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  62423. if (!texture.isCube) {
  62424. // Only supports cube Textures currently.
  62425. return null;
  62426. }
  62427. var size = texture.getSize().width;
  62428. var right = texture.readPixels(0);
  62429. var left = texture.readPixels(1);
  62430. var up;
  62431. var down;
  62432. if (texture.isRenderTarget) {
  62433. up = texture.readPixels(3);
  62434. down = texture.readPixels(2);
  62435. }
  62436. else {
  62437. up = texture.readPixels(2);
  62438. down = texture.readPixels(3);
  62439. }
  62440. var front = texture.readPixels(4);
  62441. var back = texture.readPixels(5);
  62442. var gammaSpace = texture.gammaSpace;
  62443. // Always read as RGBA.
  62444. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  62445. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62446. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62447. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62448. }
  62449. var cubeInfo = {
  62450. size: size,
  62451. right: right,
  62452. left: left,
  62453. up: up,
  62454. down: down,
  62455. front: front,
  62456. back: back,
  62457. format: format,
  62458. type: type,
  62459. gammaSpace: gammaSpace,
  62460. };
  62461. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  62462. };
  62463. /**
  62464. * Converts a cubemap to the according Spherical Polynomial data.
  62465. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62466. *
  62467. * @param cubeInfo The Cube map to extract the information from.
  62468. * @return The Spherical Polynomial data.
  62469. */
  62470. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  62471. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  62472. var totalSolidAngle = 0.0;
  62473. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  62474. var du = 2.0 / cubeInfo.size;
  62475. var dv = du;
  62476. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  62477. var minUV = du * 0.5 - 1.0;
  62478. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62479. var fileFace = this.FileFaces[faceIndex];
  62480. var dataArray = cubeInfo[fileFace.name];
  62481. var v = minUV;
  62482. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  62483. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  62484. // Because SP is still linear, so summation is fine in that basis.
  62485. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  62486. for (var y = 0; y < cubeInfo.size; y++) {
  62487. var u = minUV;
  62488. for (var x = 0; x < cubeInfo.size; x++) {
  62489. // World direction (not normalised)
  62490. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  62491. worldDirection.normalize();
  62492. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  62493. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  62494. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  62495. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  62496. // Handle Integer types.
  62497. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62498. r /= 255;
  62499. g /= 255;
  62500. b /= 255;
  62501. }
  62502. // Handle Gamma space textures.
  62503. if (cubeInfo.gammaSpace) {
  62504. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  62505. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  62506. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  62507. }
  62508. var color = new BABYLON.Color3(r, g, b);
  62509. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  62510. totalSolidAngle += deltaSolidAngle;
  62511. u += du;
  62512. }
  62513. v += dv;
  62514. }
  62515. }
  62516. // Solid angle for entire sphere is 4*pi
  62517. var sphereSolidAngle = 4.0 * Math.PI;
  62518. // Adjust the solid angle to allow for how many faces we processed.
  62519. var facesProcessed = 6.0;
  62520. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  62521. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  62522. // This is needed because the numerical integration over the cube uses a
  62523. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  62524. // and also to compensate for accumulative error due to float precision in the summation.
  62525. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  62526. sphericalHarmonics.scale(correctionFactor);
  62527. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  62528. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  62529. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  62530. };
  62531. CubeMapToSphericalPolynomialTools.FileFaces = [
  62532. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  62533. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  62534. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  62535. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  62536. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  62537. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  62538. ];
  62539. return CubeMapToSphericalPolynomialTools;
  62540. }());
  62541. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  62542. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62543. })(BABYLON || (BABYLON = {}));
  62544. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  62545. var BABYLON;
  62546. (function (BABYLON) {
  62547. var Internals;
  62548. (function (Internals) {
  62549. /**
  62550. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  62551. */
  62552. var PanoramaToCubeMapTools = /** @class */ (function () {
  62553. function PanoramaToCubeMapTools() {
  62554. }
  62555. /**
  62556. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  62557. *
  62558. * @param float32Array The source data.
  62559. * @param inputWidth The width of the input panorama.
  62560. * @param inputhHeight The height of the input panorama.
  62561. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  62562. * @return The cubemap data
  62563. */
  62564. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  62565. if (!float32Array) {
  62566. throw "ConvertPanoramaToCubemap: input cannot be null";
  62567. }
  62568. if (float32Array.length != inputWidth * inputHeight * 3) {
  62569. throw "ConvertPanoramaToCubemap: input size is wrong";
  62570. }
  62571. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  62572. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  62573. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  62574. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  62575. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  62576. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  62577. return {
  62578. front: textureFront,
  62579. back: textureBack,
  62580. left: textureLeft,
  62581. right: textureRight,
  62582. up: textureUp,
  62583. down: textureDown,
  62584. size: size,
  62585. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  62586. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  62587. gammaSpace: false,
  62588. };
  62589. };
  62590. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  62591. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  62592. var textureArray = new Float32Array(buffer);
  62593. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  62594. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  62595. var dy = 1 / texSize;
  62596. var fy = 0;
  62597. for (var y = 0; y < texSize; y++) {
  62598. var xv1 = faceData[0];
  62599. var xv2 = faceData[2];
  62600. for (var x = 0; x < texSize; x++) {
  62601. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  62602. v.normalize();
  62603. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  62604. // 3 channels per pixels
  62605. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  62606. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  62607. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  62608. xv1 = xv1.add(rotDX1);
  62609. xv2 = xv2.add(rotDX2);
  62610. }
  62611. fy += dy;
  62612. }
  62613. return textureArray;
  62614. };
  62615. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  62616. var theta = Math.atan2(vDir.z, vDir.x);
  62617. var phi = Math.acos(vDir.y);
  62618. while (theta < -Math.PI)
  62619. theta += 2 * Math.PI;
  62620. while (theta > Math.PI)
  62621. theta -= 2 * Math.PI;
  62622. var dx = theta / Math.PI;
  62623. var dy = phi / Math.PI;
  62624. // recenter.
  62625. dx = dx * 0.5 + 0.5;
  62626. var px = Math.round(dx * inputWidth);
  62627. if (px < 0)
  62628. px = 0;
  62629. else if (px >= inputWidth)
  62630. px = inputWidth - 1;
  62631. var py = Math.round(dy * inputHeight);
  62632. if (py < 0)
  62633. py = 0;
  62634. else if (py >= inputHeight)
  62635. py = inputHeight - 1;
  62636. var inputY = (inputHeight - py - 1);
  62637. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  62638. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  62639. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  62640. return {
  62641. r: r,
  62642. g: g,
  62643. b: b
  62644. };
  62645. };
  62646. PanoramaToCubeMapTools.FACE_FRONT = [
  62647. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62648. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62649. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62650. new BABYLON.Vector3(1.0, 1.0, -1.0)
  62651. ];
  62652. PanoramaToCubeMapTools.FACE_BACK = [
  62653. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62654. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62655. new BABYLON.Vector3(1.0, 1.0, 1.0),
  62656. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  62657. ];
  62658. PanoramaToCubeMapTools.FACE_RIGHT = [
  62659. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62660. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62661. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62662. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62663. ];
  62664. PanoramaToCubeMapTools.FACE_LEFT = [
  62665. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62666. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62667. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62668. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  62669. ];
  62670. PanoramaToCubeMapTools.FACE_DOWN = [
  62671. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62672. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62673. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62674. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62675. ];
  62676. PanoramaToCubeMapTools.FACE_UP = [
  62677. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62678. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62679. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62680. new BABYLON.Vector3(1.0, -1.0, -1.0)
  62681. ];
  62682. return PanoramaToCubeMapTools;
  62683. }());
  62684. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  62685. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62686. })(BABYLON || (BABYLON = {}));
  62687. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  62688. var BABYLON;
  62689. (function (BABYLON) {
  62690. var Internals;
  62691. (function (Internals) {
  62692. ;
  62693. /**
  62694. * This groups tools to convert HDR texture to native colors array.
  62695. */
  62696. var HDRTools = /** @class */ (function () {
  62697. function HDRTools() {
  62698. }
  62699. HDRTools.Ldexp = function (mantissa, exponent) {
  62700. if (exponent > 1023) {
  62701. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  62702. }
  62703. if (exponent < -1074) {
  62704. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  62705. }
  62706. return mantissa * Math.pow(2, exponent);
  62707. };
  62708. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  62709. if (exponent > 0) {
  62710. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  62711. float32array[index + 0] = red * exponent;
  62712. float32array[index + 1] = green * exponent;
  62713. float32array[index + 2] = blue * exponent;
  62714. }
  62715. else {
  62716. float32array[index + 0] = 0;
  62717. float32array[index + 1] = 0;
  62718. float32array[index + 2] = 0;
  62719. }
  62720. };
  62721. HDRTools.readStringLine = function (uint8array, startIndex) {
  62722. var line = "";
  62723. var character = "";
  62724. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  62725. character = String.fromCharCode(uint8array[i]);
  62726. if (character == "\n") {
  62727. break;
  62728. }
  62729. line += character;
  62730. }
  62731. return line;
  62732. };
  62733. /**
  62734. * Reads header information from an RGBE texture stored in a native array.
  62735. * More information on this format are available here:
  62736. * https://en.wikipedia.org/wiki/RGBE_image_format
  62737. *
  62738. * @param uint8array The binary file stored in native array.
  62739. * @return The header information.
  62740. */
  62741. HDRTools.RGBE_ReadHeader = function (uint8array) {
  62742. var height = 0;
  62743. var width = 0;
  62744. var line = this.readStringLine(uint8array, 0);
  62745. if (line[0] != '#' || line[1] != '?') {
  62746. throw "Bad HDR Format.";
  62747. }
  62748. var endOfHeader = false;
  62749. var findFormat = false;
  62750. var lineIndex = 0;
  62751. do {
  62752. lineIndex += (line.length + 1);
  62753. line = this.readStringLine(uint8array, lineIndex);
  62754. if (line == "FORMAT=32-bit_rle_rgbe") {
  62755. findFormat = true;
  62756. }
  62757. else if (line.length == 0) {
  62758. endOfHeader = true;
  62759. }
  62760. } while (!endOfHeader);
  62761. if (!findFormat) {
  62762. throw "HDR Bad header format, unsupported FORMAT";
  62763. }
  62764. lineIndex += (line.length + 1);
  62765. line = this.readStringLine(uint8array, lineIndex);
  62766. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  62767. var match = sizeRegexp.exec(line);
  62768. // TODO. Support +Y and -X if needed.
  62769. if (!match || match.length < 3) {
  62770. throw "HDR Bad header format, no size";
  62771. }
  62772. width = parseInt(match[2]);
  62773. height = parseInt(match[1]);
  62774. if (width < 8 || width > 0x7fff) {
  62775. throw "HDR Bad header format, unsupported size";
  62776. }
  62777. lineIndex += (line.length + 1);
  62778. return {
  62779. height: height,
  62780. width: width,
  62781. dataPosition: lineIndex
  62782. };
  62783. };
  62784. /**
  62785. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  62786. * This RGBE texture needs to store the information as a panorama.
  62787. *
  62788. * More information on this format are available here:
  62789. * https://en.wikipedia.org/wiki/RGBE_image_format
  62790. *
  62791. * @param buffer The binary file stored in an array buffer.
  62792. * @param size The expected size of the extracted cubemap.
  62793. * @return The Cube Map information.
  62794. */
  62795. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  62796. var uint8array = new Uint8Array(buffer);
  62797. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  62798. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62799. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  62800. return cubeMapData;
  62801. };
  62802. /**
  62803. * Returns the pixels data extracted from an RGBE texture.
  62804. * This pixels will be stored left to right up to down in the R G B order in one array.
  62805. *
  62806. * More information on this format are available here:
  62807. * https://en.wikipedia.org/wiki/RGBE_image_format
  62808. *
  62809. * @param uint8array The binary file stored in an array buffer.
  62810. * @param hdrInfo The header information of the file.
  62811. * @return The pixels data in RGB right to left up to down order.
  62812. */
  62813. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  62814. // Keep for multi format supports.
  62815. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62816. };
  62817. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  62818. var num_scanlines = hdrInfo.height;
  62819. var scanline_width = hdrInfo.width;
  62820. var a, b, c, d, count;
  62821. var dataIndex = hdrInfo.dataPosition;
  62822. var index = 0, endIndex = 0, i = 0;
  62823. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  62824. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  62825. // 3 channels of 4 bytes per pixel in float.
  62826. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  62827. var resultArray = new Float32Array(resultBuffer);
  62828. // read in each successive scanline
  62829. while (num_scanlines > 0) {
  62830. a = uint8array[dataIndex++];
  62831. b = uint8array[dataIndex++];
  62832. c = uint8array[dataIndex++];
  62833. d = uint8array[dataIndex++];
  62834. if (a != 2 || b != 2 || (c & 0x80)) {
  62835. // this file is not run length encoded
  62836. throw "HDR Bad header format, not RLE";
  62837. }
  62838. if (((c << 8) | d) != scanline_width) {
  62839. throw "HDR Bad header format, wrong scan line width";
  62840. }
  62841. index = 0;
  62842. // read each of the four channels for the scanline into the buffer
  62843. for (i = 0; i < 4; i++) {
  62844. endIndex = (i + 1) * scanline_width;
  62845. while (index < endIndex) {
  62846. a = uint8array[dataIndex++];
  62847. b = uint8array[dataIndex++];
  62848. if (a > 128) {
  62849. // a run of the same value
  62850. count = a - 128;
  62851. if ((count == 0) || (count > endIndex - index)) {
  62852. throw "HDR Bad Format, bad scanline data (run)";
  62853. }
  62854. while (count-- > 0) {
  62855. scanLineArray[index++] = b;
  62856. }
  62857. }
  62858. else {
  62859. // a non-run
  62860. count = a;
  62861. if ((count == 0) || (count > endIndex - index)) {
  62862. throw "HDR Bad Format, bad scanline data (non-run)";
  62863. }
  62864. scanLineArray[index++] = b;
  62865. if (--count > 0) {
  62866. for (var j = 0; j < count; j++) {
  62867. scanLineArray[index++] = uint8array[dataIndex++];
  62868. }
  62869. }
  62870. }
  62871. }
  62872. }
  62873. // now convert data from buffer into floats
  62874. for (i = 0; i < scanline_width; i++) {
  62875. a = scanLineArray[i];
  62876. b = scanLineArray[i + scanline_width];
  62877. c = scanLineArray[i + 2 * scanline_width];
  62878. d = scanLineArray[i + 3 * scanline_width];
  62879. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  62880. }
  62881. num_scanlines--;
  62882. }
  62883. return resultArray;
  62884. };
  62885. return HDRTools;
  62886. }());
  62887. Internals.HDRTools = HDRTools;
  62888. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62889. })(BABYLON || (BABYLON = {}));
  62890. //# sourceMappingURL=babylon.hdr.js.map
  62891. var BABYLON;
  62892. (function (BABYLON) {
  62893. /**
  62894. * This represents a texture coming from an HDR input.
  62895. *
  62896. * The only supported format is currently panorama picture stored in RGBE format.
  62897. * Example of such files can be found on HDRLib: http://hdrlib.com/
  62898. */
  62899. var HDRCubeTexture = /** @class */ (function (_super) {
  62900. __extends(HDRCubeTexture, _super);
  62901. /**
  62902. * Instantiates an HDRTexture from the following parameters.
  62903. *
  62904. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  62905. * @param scene The scene the texture will be used in
  62906. * @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.
  62907. * @param noMipmap Forces to not generate the mipmap if true
  62908. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  62909. * @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)
  62910. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  62911. */
  62912. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  62913. if (noMipmap === void 0) { noMipmap = false; }
  62914. if (generateHarmonics === void 0) { generateHarmonics = true; }
  62915. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  62916. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  62917. if (onLoad === void 0) { onLoad = null; }
  62918. if (onError === void 0) { onError = null; }
  62919. var _this = _super.call(this, scene) || this;
  62920. _this._useInGammaSpace = false;
  62921. _this._generateHarmonics = true;
  62922. _this._isBABYLONPreprocessed = false;
  62923. _this._onLoad = null;
  62924. _this._onError = null;
  62925. /**
  62926. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  62927. */
  62928. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62929. /**
  62930. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  62931. * This is usefull at run time to apply the good shader.
  62932. */
  62933. _this.isPMREM = false;
  62934. _this._isBlocking = true;
  62935. if (!url) {
  62936. return _this;
  62937. }
  62938. _this.name = url;
  62939. _this.url = url;
  62940. _this.hasAlpha = false;
  62941. _this.isCube = true;
  62942. _this._textureMatrix = BABYLON.Matrix.Identity();
  62943. _this._onLoad = onLoad;
  62944. _this._onError = onError;
  62945. _this.gammaSpace = false;
  62946. var caps = scene.getEngine().getCaps();
  62947. if (size) {
  62948. _this._isBABYLONPreprocessed = false;
  62949. _this._noMipmap = noMipmap;
  62950. _this._size = size;
  62951. _this._useInGammaSpace = useInGammaSpace;
  62952. _this._usePMREMGenerator = usePMREMGenerator &&
  62953. caps.textureLOD &&
  62954. caps.textureFloat &&
  62955. !_this._useInGammaSpace;
  62956. }
  62957. else {
  62958. _this._isBABYLONPreprocessed = true;
  62959. _this._noMipmap = false;
  62960. _this._useInGammaSpace = false;
  62961. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  62962. !_this._useInGammaSpace;
  62963. }
  62964. _this.isPMREM = _this._usePMREMGenerator;
  62965. _this._texture = _this._getFromCache(url, _this._noMipmap);
  62966. if (!_this._texture) {
  62967. if (!scene.useDelayedTextureLoading) {
  62968. _this.loadTexture();
  62969. }
  62970. else {
  62971. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62972. }
  62973. }
  62974. return _this;
  62975. }
  62976. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  62977. /**
  62978. * Gets wether or not the texture is blocking during loading.
  62979. */
  62980. get: function () {
  62981. return this._isBlocking;
  62982. },
  62983. /**
  62984. * Sets wether or not the texture is blocking during loading.
  62985. */
  62986. set: function (value) {
  62987. this._isBlocking = value;
  62988. },
  62989. enumerable: true,
  62990. configurable: true
  62991. });
  62992. /**
  62993. * Occurs when the file is a preprocessed .babylon.hdr file.
  62994. */
  62995. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  62996. var _this = this;
  62997. var mipLevels = 0;
  62998. var floatArrayView = null;
  62999. var scene = this.getScene();
  63000. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  63001. var mips = new Array();
  63002. if (!floatArrayView) {
  63003. return mips;
  63004. }
  63005. var startIndex = 30;
  63006. for (var level = 0; level < mipLevels; level++) {
  63007. mips.push([]);
  63008. // Fill each pixel of the mip level.
  63009. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  63010. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63011. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  63012. mips[level].push(faceData);
  63013. startIndex += faceSize;
  63014. }
  63015. }
  63016. return mips;
  63017. } : null;
  63018. var callback = function (buffer) {
  63019. var scene = _this.getScene();
  63020. if (!scene) {
  63021. return null;
  63022. }
  63023. // Create Native Array Views
  63024. var intArrayView = new Int32Array(buffer);
  63025. floatArrayView = new Float32Array(buffer);
  63026. // Fill header.
  63027. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  63028. _this._size = intArrayView[1]; // CubeMap max mip face size.
  63029. // Update Texture Information.
  63030. if (!_this._texture) {
  63031. return null;
  63032. }
  63033. _this._texture.updateSize(_this._size, _this._size);
  63034. // Fill polynomial information.
  63035. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  63036. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  63037. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  63038. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  63039. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  63040. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  63041. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  63042. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  63043. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  63044. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  63045. _this.sphericalPolynomial = sphericalPolynomial;
  63046. // Fill pixel data.
  63047. mipLevels = intArrayView[29]; // Number of mip levels.
  63048. var startIndex = 30;
  63049. var data = [];
  63050. var faceSize = Math.pow(_this._size, 2) * 3;
  63051. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63052. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  63053. startIndex += faceSize;
  63054. }
  63055. var results = [];
  63056. var byteArray = null;
  63057. // Push each faces.
  63058. for (var k = 0; k < 6; k++) {
  63059. var dataFace = null;
  63060. // To be deprecated.
  63061. if (version === 1) {
  63062. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  63063. dataFace = data[j];
  63064. }
  63065. // If special cases.
  63066. if (!mipmapGenerator && dataFace) {
  63067. if (!scene.getEngine().getCaps().textureFloat) {
  63068. // 3 channels of 1 bytes per pixel in bytes.
  63069. var byteBuffer = new ArrayBuffer(faceSize);
  63070. byteArray = new Uint8Array(byteBuffer);
  63071. }
  63072. for (var i = 0; i < _this._size * _this._size; i++) {
  63073. // Put in gamma space if requested.
  63074. if (_this._useInGammaSpace) {
  63075. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63076. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63077. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63078. }
  63079. // Convert to int texture for fallback.
  63080. if (byteArray) {
  63081. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63082. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63083. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63084. // May use luminance instead if the result is not accurate.
  63085. var max = Math.max(Math.max(r, g), b);
  63086. if (max > 255) {
  63087. var scale = 255 / max;
  63088. r *= scale;
  63089. g *= scale;
  63090. b *= scale;
  63091. }
  63092. byteArray[(i * 3) + 0] = r;
  63093. byteArray[(i * 3) + 1] = g;
  63094. byteArray[(i * 3) + 2] = b;
  63095. }
  63096. }
  63097. }
  63098. // Fill the array accordingly.
  63099. if (byteArray) {
  63100. results.push(byteArray);
  63101. }
  63102. else {
  63103. results.push(dataFace);
  63104. }
  63105. }
  63106. return results;
  63107. };
  63108. if (scene) {
  63109. 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);
  63110. }
  63111. };
  63112. /**
  63113. * Occurs when the file is raw .hdr file.
  63114. */
  63115. HDRCubeTexture.prototype.loadHDRTexture = function () {
  63116. var _this = this;
  63117. var callback = function (buffer) {
  63118. var scene = _this.getScene();
  63119. if (!scene) {
  63120. return null;
  63121. }
  63122. // Extract the raw linear data.
  63123. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  63124. // Generate harmonics if needed.
  63125. if (_this._generateHarmonics) {
  63126. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  63127. _this.sphericalPolynomial = sphericalPolynomial;
  63128. }
  63129. var results = [];
  63130. var byteArray = null;
  63131. // Push each faces.
  63132. for (var j = 0; j < 6; j++) {
  63133. // Create uintarray fallback.
  63134. if (!scene.getEngine().getCaps().textureFloat) {
  63135. // 3 channels of 1 bytes per pixel in bytes.
  63136. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  63137. byteArray = new Uint8Array(byteBuffer);
  63138. }
  63139. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  63140. // If special cases.
  63141. if (_this._useInGammaSpace || byteArray) {
  63142. for (var i = 0; i < _this._size * _this._size; i++) {
  63143. // Put in gamma space if requested.
  63144. if (_this._useInGammaSpace) {
  63145. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63146. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63147. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63148. }
  63149. // Convert to int texture for fallback.
  63150. if (byteArray) {
  63151. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63152. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63153. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63154. // May use luminance instead if the result is not accurate.
  63155. var max = Math.max(Math.max(r, g), b);
  63156. if (max > 255) {
  63157. var scale = 255 / max;
  63158. r *= scale;
  63159. g *= scale;
  63160. b *= scale;
  63161. }
  63162. byteArray[(i * 3) + 0] = r;
  63163. byteArray[(i * 3) + 1] = g;
  63164. byteArray[(i * 3) + 2] = b;
  63165. }
  63166. }
  63167. }
  63168. if (byteArray) {
  63169. results.push(byteArray);
  63170. }
  63171. else {
  63172. results.push(dataFace);
  63173. }
  63174. }
  63175. return results;
  63176. };
  63177. var mipmapGenerator = null;
  63178. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63179. // if (!this._noMipmap &&
  63180. // this._usePMREMGenerator) {
  63181. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63182. // // Custom setup of the generator matching with the PBR shader values.
  63183. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63184. // this._size,
  63185. // this._size,
  63186. // 0,
  63187. // 3,
  63188. // this.getScene().getEngine().getCaps().textureFloat,
  63189. // 2048,
  63190. // 0.25,
  63191. // false,
  63192. // true);
  63193. // return generator.filterCubeMap();
  63194. // };
  63195. // }
  63196. var scene = this.getScene();
  63197. if (scene) {
  63198. 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);
  63199. }
  63200. };
  63201. /**
  63202. * Starts the loading process of the texture.
  63203. */
  63204. HDRCubeTexture.prototype.loadTexture = function () {
  63205. if (this._isBABYLONPreprocessed) {
  63206. this.loadBabylonTexture();
  63207. }
  63208. else {
  63209. this.loadHDRTexture();
  63210. }
  63211. };
  63212. HDRCubeTexture.prototype.clone = function () {
  63213. var scene = this.getScene();
  63214. if (!scene) {
  63215. return this;
  63216. }
  63217. var size = (this._isBABYLONPreprocessed ? null : this._size);
  63218. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  63219. // Base texture
  63220. newTexture.level = this.level;
  63221. newTexture.wrapU = this.wrapU;
  63222. newTexture.wrapV = this.wrapV;
  63223. newTexture.coordinatesIndex = this.coordinatesIndex;
  63224. newTexture.coordinatesMode = this.coordinatesMode;
  63225. return newTexture;
  63226. };
  63227. // Methods
  63228. HDRCubeTexture.prototype.delayLoad = function () {
  63229. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63230. return;
  63231. }
  63232. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63233. this._texture = this._getFromCache(this.url, this._noMipmap);
  63234. if (!this._texture) {
  63235. this.loadTexture();
  63236. }
  63237. };
  63238. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  63239. return this._textureMatrix;
  63240. };
  63241. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63242. this._textureMatrix = value;
  63243. };
  63244. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63245. var texture = null;
  63246. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63247. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  63248. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  63249. texture.name = parsedTexture.name;
  63250. texture.hasAlpha = parsedTexture.hasAlpha;
  63251. texture.level = parsedTexture.level;
  63252. texture.coordinatesMode = parsedTexture.coordinatesMode;
  63253. texture.isBlocking = parsedTexture.isBlocking;
  63254. }
  63255. return texture;
  63256. };
  63257. HDRCubeTexture.prototype.serialize = function () {
  63258. if (!this.name) {
  63259. return null;
  63260. }
  63261. var serializationObject = {};
  63262. serializationObject.name = this.name;
  63263. serializationObject.hasAlpha = this.hasAlpha;
  63264. serializationObject.isCube = true;
  63265. serializationObject.level = this.level;
  63266. serializationObject.size = this._size;
  63267. serializationObject.coordinatesMode = this.coordinatesMode;
  63268. serializationObject.useInGammaSpace = this._useInGammaSpace;
  63269. serializationObject.generateHarmonics = this._generateHarmonics;
  63270. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  63271. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  63272. serializationObject.customType = "BABYLON.HDRCubeTexture";
  63273. serializationObject.noMipmap = this._noMipmap;
  63274. serializationObject.isBlocking = this._isBlocking;
  63275. return serializationObject;
  63276. };
  63277. /**
  63278. * Saves as a file the data contained in the texture in a binary format.
  63279. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63280. * as the spherical used in the lighting.
  63281. * @param url The HDR file url.
  63282. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63283. * @param onError Method called if any error happens during download.
  63284. * @return The packed binary data.
  63285. */
  63286. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  63287. if (onError === void 0) { onError = null; }
  63288. var callback = function (buffer) {
  63289. var data = new Blob([buffer], { type: 'application/octet-stream' });
  63290. // Returns a URL you can use as a href.
  63291. var objUrl = window.URL.createObjectURL(data);
  63292. // Simulates a link to it and click to dowload.
  63293. var a = document.createElement("a");
  63294. document.body.appendChild(a);
  63295. a.style.display = "none";
  63296. a.href = objUrl;
  63297. a.download = "envmap.babylon.hdr";
  63298. a.click();
  63299. };
  63300. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  63301. };
  63302. /**
  63303. * Serializes the data contained in the texture in a binary format.
  63304. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63305. * as the spherical used in the lighting.
  63306. * @param url The HDR file url.
  63307. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63308. * @param onError Method called if any error happens during download.
  63309. * @return The packed binary data.
  63310. */
  63311. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  63312. if (onError === void 0) { onError = null; }
  63313. // Needs the url tho create the texture.
  63314. if (!url) {
  63315. return;
  63316. }
  63317. // Check Power of two size.
  63318. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  63319. return;
  63320. }
  63321. // Coming Back in 3.x.
  63322. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  63323. };
  63324. HDRCubeTexture._facesMapping = [
  63325. "right",
  63326. "left",
  63327. "up",
  63328. "down",
  63329. "front",
  63330. "back"
  63331. ];
  63332. return HDRCubeTexture;
  63333. }(BABYLON.BaseTexture));
  63334. BABYLON.HDRCubeTexture = HDRCubeTexture;
  63335. })(BABYLON || (BABYLON = {}));
  63336. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  63337. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  63338. // Huge respect for a such great lib.
  63339. // Earcut license:
  63340. // Copyright (c) 2016, Mapbox
  63341. //
  63342. // Permission to use, copy, modify, and/or distribute this software for any purpose
  63343. // with or without fee is hereby granted, provided that the above copyright notice
  63344. // and this permission notice appear in all copies.
  63345. //
  63346. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  63347. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  63348. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  63349. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  63350. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  63351. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  63352. // THIS SOFTWARE.
  63353. var Earcut;
  63354. (function (Earcut) {
  63355. /**
  63356. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  63357. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  63358. * @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).
  63359. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  63360. */
  63361. function earcut(data, holeIndices, dim) {
  63362. dim = dim || 2;
  63363. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  63364. if (!outerNode)
  63365. return triangles;
  63366. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  63367. if (hasHoles)
  63368. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  63369. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  63370. if (data.length > 80 * dim) {
  63371. minX = maxX = data[0];
  63372. minY = maxY = data[1];
  63373. for (var i = dim; i < outerLen; i += dim) {
  63374. x = data[i];
  63375. y = data[i + 1];
  63376. if (x < minX)
  63377. minX = x;
  63378. if (y < minY)
  63379. minY = y;
  63380. if (x > maxX)
  63381. maxX = x;
  63382. if (y > maxY)
  63383. maxY = y;
  63384. }
  63385. // minX, minY and size are later used to transform coords into integers for z-order calculation
  63386. size = Math.max(maxX - minX, maxY - minY);
  63387. }
  63388. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  63389. return triangles;
  63390. }
  63391. Earcut.earcut = earcut;
  63392. var Node = /** @class */ (function () {
  63393. function Node(i, x, y) {
  63394. this.i = i;
  63395. this.x = x;
  63396. this.y = y;
  63397. this.prev = null;
  63398. this.next = null;
  63399. this.z = null;
  63400. this.prevZ = null;
  63401. this.nextZ = null;
  63402. this.steiner = false;
  63403. }
  63404. return Node;
  63405. }());
  63406. // create a circular doubly linked list from polygon points in the specified winding order
  63407. function linkedList(data, start, end, dim, clockwise) {
  63408. var i, last = null;
  63409. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  63410. for (i = start; i < end; i += dim)
  63411. last = insertNode(i, data[i], data[i + 1], last);
  63412. }
  63413. else {
  63414. for (i = end - dim; i >= start; i -= dim)
  63415. last = insertNode(i, data[i], data[i + 1], last);
  63416. }
  63417. if (last && equals(last, last.next)) {
  63418. removeNode(last);
  63419. last = last.next;
  63420. }
  63421. return last;
  63422. }
  63423. // eliminate colinear or duplicate points
  63424. function filterPoints(start, end) {
  63425. if (!start)
  63426. return start;
  63427. if (!end)
  63428. end = start;
  63429. var p = start, again;
  63430. do {
  63431. again = false;
  63432. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  63433. removeNode(p);
  63434. p = end = p.prev;
  63435. if (p === p.next)
  63436. return undefined;
  63437. again = true;
  63438. }
  63439. else {
  63440. p = p.next;
  63441. }
  63442. } while (again || p !== end);
  63443. return end;
  63444. }
  63445. // main ear slicing loop which triangulates a polygon (given as a linked list)
  63446. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  63447. if (!ear)
  63448. return;
  63449. // interlink polygon nodes in z-order
  63450. if (!pass && size)
  63451. indexCurve(ear, minX, minY, size);
  63452. var stop = ear, prev, next;
  63453. // iterate through ears, slicing them one by one
  63454. while (ear.prev !== ear.next) {
  63455. prev = ear.prev;
  63456. next = ear.next;
  63457. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  63458. // cut off the triangle
  63459. triangles.push(prev.i / dim);
  63460. triangles.push(ear.i / dim);
  63461. triangles.push(next.i / dim);
  63462. removeNode(ear);
  63463. // skipping the next vertice leads to less sliver triangles
  63464. ear = next.next;
  63465. stop = next.next;
  63466. continue;
  63467. }
  63468. ear = next;
  63469. // if we looped through the whole remaining polygon and can't find any more ears
  63470. if (ear === stop) {
  63471. // try filtering points and slicing again
  63472. if (!pass) {
  63473. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  63474. // if this didn't work, try curing all small self-intersections locally
  63475. }
  63476. else if (pass === 1) {
  63477. ear = cureLocalIntersections(ear, triangles, dim);
  63478. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  63479. // as a last resort, try splitting the remaining polygon into two
  63480. }
  63481. else if (pass === 2) {
  63482. splitEarcut(ear, triangles, dim, minX, minY, size);
  63483. }
  63484. break;
  63485. }
  63486. }
  63487. }
  63488. // check whether a polygon node forms a valid ear with adjacent nodes
  63489. function isEar(ear) {
  63490. var a = ear.prev, b = ear, c = ear.next;
  63491. if (area(a, b, c) >= 0)
  63492. return false; // reflex, can't be an ear
  63493. // now make sure we don't have other points inside the potential ear
  63494. var p = ear.next.next;
  63495. while (p !== ear.prev) {
  63496. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63497. area(p.prev, p, p.next) >= 0)
  63498. return false;
  63499. p = p.next;
  63500. }
  63501. return true;
  63502. }
  63503. function isEarHashed(ear, minX, minY, size) {
  63504. var a = ear.prev, b = ear, c = ear.next;
  63505. if (area(a, b, c) >= 0)
  63506. return false; // reflex, can't be an ear
  63507. // triangle bbox; min & max are calculated like this for speed
  63508. 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);
  63509. // z-order range for the current triangle bbox;
  63510. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  63511. // first look for points inside the triangle in increasing z-order
  63512. var p = ear.nextZ;
  63513. while (p && p.z <= maxZ) {
  63514. if (p !== ear.prev &&
  63515. p !== ear.next &&
  63516. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63517. area(p.prev, p, p.next) >= 0)
  63518. return false;
  63519. p = p.nextZ;
  63520. }
  63521. // then look for points in decreasing z-order
  63522. p = ear.prevZ;
  63523. while (p && p.z >= minZ) {
  63524. if (p !== ear.prev &&
  63525. p !== ear.next &&
  63526. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63527. area(p.prev, p, p.next) >= 0)
  63528. return false;
  63529. p = p.prevZ;
  63530. }
  63531. return true;
  63532. }
  63533. // go through all polygon nodes and cure small local self-intersections
  63534. function cureLocalIntersections(start, triangles, dim) {
  63535. var p = start;
  63536. do {
  63537. var a = p.prev, b = p.next.next;
  63538. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  63539. triangles.push(a.i / dim);
  63540. triangles.push(p.i / dim);
  63541. triangles.push(b.i / dim);
  63542. // remove two nodes involved
  63543. removeNode(p);
  63544. removeNode(p.next);
  63545. p = start = b;
  63546. }
  63547. p = p.next;
  63548. } while (p !== start);
  63549. return p;
  63550. }
  63551. // try splitting polygon into two and triangulate them independently
  63552. function splitEarcut(start, triangles, dim, minX, minY, size) {
  63553. // look for a valid diagonal that divides the polygon into two
  63554. var a = start;
  63555. do {
  63556. var b = a.next.next;
  63557. while (b !== a.prev) {
  63558. if (a.i !== b.i && isValidDiagonal(a, b)) {
  63559. // split the polygon in two by the diagonal
  63560. var c = splitPolygon(a, b);
  63561. // filter colinear points around the cuts
  63562. a = filterPoints(a, a.next);
  63563. c = filterPoints(c, c.next);
  63564. // run earcut on each half
  63565. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  63566. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  63567. return;
  63568. }
  63569. b = b.next;
  63570. }
  63571. a = a.next;
  63572. } while (a !== start);
  63573. }
  63574. // link every hole into the outer loop, producing a single-ring polygon without holes
  63575. function eliminateHoles(data, holeIndices, outerNode, dim) {
  63576. var queue = [], i, len, start, end, list;
  63577. for (i = 0, len = holeIndices.length; i < len; i++) {
  63578. start = holeIndices[i] * dim;
  63579. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63580. list = linkedList(data, start, end, dim, false);
  63581. if (list === list.next)
  63582. list.steiner = true;
  63583. queue.push(getLeftmost(list));
  63584. }
  63585. queue.sort(compareX);
  63586. // process holes from left to right
  63587. for (i = 0; i < queue.length; i++) {
  63588. eliminateHole(queue[i], outerNode);
  63589. outerNode = filterPoints(outerNode, outerNode.next);
  63590. }
  63591. return outerNode;
  63592. }
  63593. function compareX(a, b) {
  63594. return a.x - b.x;
  63595. }
  63596. // find a bridge between vertices that connects hole with an outer ring and and link it
  63597. function eliminateHole(hole, outerNode) {
  63598. outerNode = findHoleBridge(hole, outerNode);
  63599. if (outerNode) {
  63600. var b = splitPolygon(outerNode, hole);
  63601. filterPoints(b, b.next);
  63602. }
  63603. }
  63604. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  63605. function findHoleBridge(hole, outerNode) {
  63606. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  63607. // find a segment intersected by a ray from the hole's leftmost point to the left;
  63608. // segment's endpoint with lesser x will be potential connection point
  63609. do {
  63610. if (hy <= p.y && hy >= p.next.y) {
  63611. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  63612. if (x <= hx && x > qx) {
  63613. qx = x;
  63614. if (x === hx) {
  63615. if (hy === p.y)
  63616. return p;
  63617. if (hy === p.next.y)
  63618. return p.next;
  63619. }
  63620. m = p.x < p.next.x ? p : p.next;
  63621. }
  63622. }
  63623. p = p.next;
  63624. } while (p !== outerNode);
  63625. if (!m)
  63626. return null;
  63627. if (hx === qx)
  63628. return m.prev; // hole touches outer segment; pick lower endpoint
  63629. // look for points inside the triangle of hole point, segment intersection and endpoint;
  63630. // if there are no points found, we have a valid connection;
  63631. // otherwise choose the point of the minimum angle with the ray as connection point
  63632. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  63633. p = m.next;
  63634. while (p !== stop) {
  63635. if (hx >= p.x &&
  63636. p.x >= mx &&
  63637. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  63638. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  63639. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  63640. m = p;
  63641. tanMin = tan;
  63642. }
  63643. }
  63644. p = p.next;
  63645. }
  63646. return m;
  63647. }
  63648. // interlink polygon nodes in z-order
  63649. function indexCurve(start, minX, minY, size) {
  63650. var p = start;
  63651. do {
  63652. if (p.z === null)
  63653. p.z = zOrder(p.x, p.y, minX, minY, size);
  63654. p.prevZ = p.prev;
  63655. p.nextZ = p.next;
  63656. p = p.next;
  63657. } while (p !== start);
  63658. p.prevZ.nextZ = null;
  63659. p.prevZ = null;
  63660. sortLinked(p);
  63661. }
  63662. // Simon Tatham's linked list merge sort algorithm
  63663. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  63664. function sortLinked(list) {
  63665. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  63666. do {
  63667. p = list;
  63668. list = null;
  63669. tail = null;
  63670. numMerges = 0;
  63671. while (p) {
  63672. numMerges++;
  63673. q = p;
  63674. pSize = 0;
  63675. for (i = 0; i < inSize; i++) {
  63676. pSize++;
  63677. q = q.nextZ;
  63678. if (!q)
  63679. break;
  63680. }
  63681. qSize = inSize;
  63682. while (pSize > 0 || (qSize > 0 && q)) {
  63683. if (pSize === 0) {
  63684. e = q;
  63685. q = q.nextZ;
  63686. qSize--;
  63687. }
  63688. else if (qSize === 0 || !q) {
  63689. e = p;
  63690. p = p.nextZ;
  63691. pSize--;
  63692. }
  63693. else if (p.z <= q.z) {
  63694. e = p;
  63695. p = p.nextZ;
  63696. pSize--;
  63697. }
  63698. else {
  63699. e = q;
  63700. q = q.nextZ;
  63701. qSize--;
  63702. }
  63703. if (tail)
  63704. tail.nextZ = e;
  63705. else
  63706. list = e;
  63707. e.prevZ = tail;
  63708. tail = e;
  63709. }
  63710. p = q;
  63711. }
  63712. tail.nextZ = null;
  63713. inSize *= 2;
  63714. } while (numMerges > 1);
  63715. return list;
  63716. }
  63717. // z-order of a point given coords and size of the data bounding box
  63718. function zOrder(x, y, minX, minY, size) {
  63719. // coords are transformed into non-negative 15-bit integer range
  63720. x = 32767 * (x - minX) / size;
  63721. y = 32767 * (y - minY) / size;
  63722. x = (x | (x << 8)) & 0x00FF00FF;
  63723. x = (x | (x << 4)) & 0x0F0F0F0F;
  63724. x = (x | (x << 2)) & 0x33333333;
  63725. x = (x | (x << 1)) & 0x55555555;
  63726. y = (y | (y << 8)) & 0x00FF00FF;
  63727. y = (y | (y << 4)) & 0x0F0F0F0F;
  63728. y = (y | (y << 2)) & 0x33333333;
  63729. y = (y | (y << 1)) & 0x55555555;
  63730. return x | (y << 1);
  63731. }
  63732. // find the leftmost node of a polygon ring
  63733. function getLeftmost(start) {
  63734. var p = start, leftmost = start;
  63735. do {
  63736. if (p.x < leftmost.x)
  63737. leftmost = p;
  63738. p = p.next;
  63739. } while (p !== start);
  63740. return leftmost;
  63741. }
  63742. // check if a point lies within a convex triangle
  63743. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  63744. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  63745. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  63746. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  63747. }
  63748. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  63749. function isValidDiagonal(a, b) {
  63750. return a.next.i !== b.i &&
  63751. a.prev.i !== b.i &&
  63752. !intersectsPolygon(a, b) &&
  63753. locallyInside(a, b) &&
  63754. locallyInside(b, a) &&
  63755. middleInside(a, b);
  63756. }
  63757. // signed area of a triangle
  63758. function area(p, q, r) {
  63759. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  63760. }
  63761. // check if two points are equal
  63762. function equals(p1, p2) {
  63763. return p1.x === p2.x && p1.y === p2.y;
  63764. }
  63765. // check if two segments intersect
  63766. function intersects(p1, q1, p2, q2) {
  63767. if ((equals(p1, q1) && equals(p2, q2)) ||
  63768. (equals(p1, q2) && equals(p2, q1)))
  63769. return true;
  63770. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  63771. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  63772. }
  63773. // check if a polygon diagonal intersects any polygon segments
  63774. function intersectsPolygon(a, b) {
  63775. var p = a;
  63776. do {
  63777. if (p.i !== a.i &&
  63778. p.next.i !== a.i &&
  63779. p.i !== b.i &&
  63780. p.next.i !== b.i &&
  63781. intersects(p, p.next, a, b))
  63782. return true;
  63783. p = p.next;
  63784. } while (p !== a);
  63785. return false;
  63786. }
  63787. // check if a polygon diagonal is locally inside the polygon
  63788. function locallyInside(a, b) {
  63789. return area(a.prev, a, a.next) < 0
  63790. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  63791. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  63792. }
  63793. // check if the middle point of a polygon diagonal is inside the polygon
  63794. function middleInside(a, b) {
  63795. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  63796. do {
  63797. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  63798. inside = !inside;
  63799. p = p.next;
  63800. } while (p !== a);
  63801. return inside;
  63802. }
  63803. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  63804. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  63805. function splitPolygon(a, b) {
  63806. 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;
  63807. a.next = b;
  63808. b.prev = a;
  63809. a2.next = an;
  63810. an.prev = a2;
  63811. b2.next = a2;
  63812. a2.prev = b2;
  63813. bp.next = b2;
  63814. b2.prev = bp;
  63815. return b2;
  63816. }
  63817. // create a node and optionally link it with previous one (in a circular doubly linked list)
  63818. function insertNode(i, x, y, last) {
  63819. var p = new Node(i, x, y);
  63820. if (!last) {
  63821. p.prev = p;
  63822. p.next = p;
  63823. }
  63824. else {
  63825. p.next = last.next;
  63826. p.prev = last;
  63827. last.next.prev = p;
  63828. last.next = p;
  63829. }
  63830. return p;
  63831. }
  63832. function removeNode(p) {
  63833. p.next.prev = p.prev;
  63834. p.prev.next = p.next;
  63835. if (p.prevZ)
  63836. p.prevZ.nextZ = p.nextZ;
  63837. if (p.nextZ)
  63838. p.nextZ.prevZ = p.prevZ;
  63839. }
  63840. /**
  63841. * return a percentage difference between the polygon area and its triangulation area;
  63842. * used to verify correctness of triangulation
  63843. */
  63844. function deviation(data, holeIndices, dim, triangles) {
  63845. var hasHoles = holeIndices && holeIndices.length;
  63846. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  63847. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  63848. if (hasHoles) {
  63849. for (var i = 0, len = holeIndices.length; i < len; i++) {
  63850. var start = holeIndices[i] * dim;
  63851. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63852. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  63853. }
  63854. }
  63855. var trianglesArea = 0;
  63856. for (i = 0; i < triangles.length; i += 3) {
  63857. var a = triangles[i] * dim;
  63858. var b = triangles[i + 1] * dim;
  63859. var c = triangles[i + 2] * dim;
  63860. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  63861. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  63862. }
  63863. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  63864. }
  63865. Earcut.deviation = deviation;
  63866. ;
  63867. function signedArea(data, start, end, dim) {
  63868. var sum = 0;
  63869. for (var i = start, j = end - dim; i < end; i += dim) {
  63870. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  63871. j = i;
  63872. }
  63873. return sum;
  63874. }
  63875. /**
  63876. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  63877. */
  63878. function flatten(data) {
  63879. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  63880. for (var i = 0; i < data.length; i++) {
  63881. for (var j = 0; j < data[i].length; j++) {
  63882. for (var d = 0; d < dim; d++)
  63883. result.vertices.push(data[i][j][d]);
  63884. }
  63885. if (i > 0) {
  63886. holeIndex += data[i - 1].length;
  63887. result.holes.push(holeIndex);
  63888. }
  63889. }
  63890. return result;
  63891. }
  63892. Earcut.flatten = flatten;
  63893. ;
  63894. })(Earcut || (Earcut = {}));
  63895. //# sourceMappingURL=babylon.earcut.js.map
  63896. var BABYLON;
  63897. (function (BABYLON) {
  63898. var IndexedVector2 = /** @class */ (function (_super) {
  63899. __extends(IndexedVector2, _super);
  63900. function IndexedVector2(original, index) {
  63901. var _this = _super.call(this, original.x, original.y) || this;
  63902. _this.index = index;
  63903. return _this;
  63904. }
  63905. return IndexedVector2;
  63906. }(BABYLON.Vector2));
  63907. var PolygonPoints = /** @class */ (function () {
  63908. function PolygonPoints() {
  63909. this.elements = new Array();
  63910. }
  63911. PolygonPoints.prototype.add = function (originalPoints) {
  63912. var _this = this;
  63913. var result = new Array();
  63914. originalPoints.forEach(function (point) {
  63915. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  63916. var newPoint = new IndexedVector2(point, _this.elements.length);
  63917. result.push(newPoint);
  63918. _this.elements.push(newPoint);
  63919. }
  63920. });
  63921. return result;
  63922. };
  63923. PolygonPoints.prototype.computeBounds = function () {
  63924. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63925. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63926. this.elements.forEach(function (point) {
  63927. // x
  63928. if (point.x < lmin.x) {
  63929. lmin.x = point.x;
  63930. }
  63931. else if (point.x > lmax.x) {
  63932. lmax.x = point.x;
  63933. }
  63934. // y
  63935. if (point.y < lmin.y) {
  63936. lmin.y = point.y;
  63937. }
  63938. else if (point.y > lmax.y) {
  63939. lmax.y = point.y;
  63940. }
  63941. });
  63942. return {
  63943. min: lmin,
  63944. max: lmax,
  63945. width: lmax.x - lmin.x,
  63946. height: lmax.y - lmin.y
  63947. };
  63948. };
  63949. return PolygonPoints;
  63950. }());
  63951. var Polygon = /** @class */ (function () {
  63952. function Polygon() {
  63953. }
  63954. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  63955. return [
  63956. new BABYLON.Vector2(xmin, ymin),
  63957. new BABYLON.Vector2(xmax, ymin),
  63958. new BABYLON.Vector2(xmax, ymax),
  63959. new BABYLON.Vector2(xmin, ymax)
  63960. ];
  63961. };
  63962. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  63963. if (cx === void 0) { cx = 0; }
  63964. if (cy === void 0) { cy = 0; }
  63965. if (numberOfSides === void 0) { numberOfSides = 32; }
  63966. var result = new Array();
  63967. var angle = 0;
  63968. var increment = (Math.PI * 2) / numberOfSides;
  63969. for (var i = 0; i < numberOfSides; i++) {
  63970. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  63971. angle -= increment;
  63972. }
  63973. return result;
  63974. };
  63975. Polygon.Parse = function (input) {
  63976. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  63977. var i, result = [];
  63978. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  63979. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  63980. }
  63981. return result;
  63982. };
  63983. Polygon.StartingAt = function (x, y) {
  63984. return BABYLON.Path2.StartingAt(x, y);
  63985. };
  63986. return Polygon;
  63987. }());
  63988. BABYLON.Polygon = Polygon;
  63989. var PolygonMeshBuilder = /** @class */ (function () {
  63990. function PolygonMeshBuilder(name, contours, scene) {
  63991. this._points = new PolygonPoints();
  63992. this._outlinepoints = new PolygonPoints();
  63993. this._holes = new Array();
  63994. this._epoints = new Array();
  63995. this._eholes = new Array();
  63996. this._name = name;
  63997. this._scene = scene;
  63998. var points;
  63999. if (contours instanceof BABYLON.Path2) {
  64000. points = contours.getPoints();
  64001. }
  64002. else {
  64003. points = contours;
  64004. }
  64005. this._addToepoint(points);
  64006. this._points.add(points);
  64007. this._outlinepoints.add(points);
  64008. }
  64009. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  64010. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  64011. var p = points_1[_i];
  64012. this._epoints.push(p.x, p.y);
  64013. }
  64014. };
  64015. PolygonMeshBuilder.prototype.addHole = function (hole) {
  64016. this._points.add(hole);
  64017. var holepoints = new PolygonPoints();
  64018. holepoints.add(hole);
  64019. this._holes.push(holepoints);
  64020. this._eholes.push(this._epoints.length / 2);
  64021. this._addToepoint(hole);
  64022. return this;
  64023. };
  64024. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  64025. var _this = this;
  64026. if (updatable === void 0) { updatable = false; }
  64027. if (depth === void 0) { depth = 0; }
  64028. var result = new BABYLON.Mesh(this._name, this._scene);
  64029. var normals = new Array();
  64030. var positions = new Array();
  64031. var uvs = new Array();
  64032. var bounds = this._points.computeBounds();
  64033. this._points.elements.forEach(function (p) {
  64034. normals.push(0, 1.0, 0);
  64035. positions.push(p.x, 0, p.y);
  64036. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  64037. });
  64038. var indices = new Array();
  64039. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  64040. for (var i = 0; i < res.length; i++) {
  64041. indices.push(res[i]);
  64042. }
  64043. if (depth > 0) {
  64044. var positionscount = (positions.length / 3); //get the current pointcount
  64045. this._points.elements.forEach(function (p) {
  64046. normals.push(0, -1.0, 0);
  64047. positions.push(p.x, -depth, p.y);
  64048. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  64049. });
  64050. var totalCount = indices.length;
  64051. for (var i = 0; i < totalCount; i += 3) {
  64052. var i0 = indices[i + 0];
  64053. var i1 = indices[i + 1];
  64054. var i2 = indices[i + 2];
  64055. indices.push(i2 + positionscount);
  64056. indices.push(i1 + positionscount);
  64057. indices.push(i0 + positionscount);
  64058. }
  64059. //Add the sides
  64060. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  64061. this._holes.forEach(function (hole) {
  64062. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  64063. });
  64064. }
  64065. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  64066. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  64067. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  64068. result.setIndices(indices);
  64069. return result;
  64070. };
  64071. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  64072. var StartIndex = positions.length / 3;
  64073. var ulength = 0;
  64074. for (var i = 0; i < points.elements.length; i++) {
  64075. var p = points.elements[i];
  64076. var p1;
  64077. if ((i + 1) > points.elements.length - 1) {
  64078. p1 = points.elements[0];
  64079. }
  64080. else {
  64081. p1 = points.elements[i + 1];
  64082. }
  64083. positions.push(p.x, 0, p.y);
  64084. positions.push(p.x, -depth, p.y);
  64085. positions.push(p1.x, 0, p1.y);
  64086. positions.push(p1.x, -depth, p1.y);
  64087. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  64088. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  64089. var v3 = v2.subtract(v1);
  64090. var v4 = new BABYLON.Vector3(0, 1, 0);
  64091. var vn = BABYLON.Vector3.Cross(v3, v4);
  64092. vn = vn.normalize();
  64093. uvs.push(ulength / bounds.width, 0);
  64094. uvs.push(ulength / bounds.width, 1);
  64095. ulength += v3.length();
  64096. uvs.push((ulength / bounds.width), 0);
  64097. uvs.push((ulength / bounds.width), 1);
  64098. if (!flip) {
  64099. normals.push(-vn.x, -vn.y, -vn.z);
  64100. normals.push(-vn.x, -vn.y, -vn.z);
  64101. normals.push(-vn.x, -vn.y, -vn.z);
  64102. normals.push(-vn.x, -vn.y, -vn.z);
  64103. indices.push(StartIndex);
  64104. indices.push(StartIndex + 1);
  64105. indices.push(StartIndex + 2);
  64106. indices.push(StartIndex + 1);
  64107. indices.push(StartIndex + 3);
  64108. indices.push(StartIndex + 2);
  64109. }
  64110. else {
  64111. normals.push(vn.x, vn.y, vn.z);
  64112. normals.push(vn.x, vn.y, vn.z);
  64113. normals.push(vn.x, vn.y, vn.z);
  64114. normals.push(vn.x, vn.y, vn.z);
  64115. indices.push(StartIndex);
  64116. indices.push(StartIndex + 2);
  64117. indices.push(StartIndex + 1);
  64118. indices.push(StartIndex + 1);
  64119. indices.push(StartIndex + 2);
  64120. indices.push(StartIndex + 3);
  64121. }
  64122. StartIndex += 4;
  64123. }
  64124. ;
  64125. };
  64126. return PolygonMeshBuilder;
  64127. }());
  64128. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  64129. })(BABYLON || (BABYLON = {}));
  64130. //# sourceMappingURL=babylon.polygonMesh.js.map
  64131. var BABYLON;
  64132. (function (BABYLON) {
  64133. // Unique ID when we import meshes from Babylon to CSG
  64134. var currentCSGMeshId = 0;
  64135. // # class Vertex
  64136. // Represents a vertex of a polygon. Use your own vertex class instead of this
  64137. // one to provide additional features like texture coordinates and vertex
  64138. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  64139. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  64140. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  64141. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  64142. // is not used anywhere else.
  64143. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  64144. var Vertex = /** @class */ (function () {
  64145. function Vertex(pos, normal, uv) {
  64146. this.pos = pos;
  64147. this.normal = normal;
  64148. this.uv = uv;
  64149. }
  64150. Vertex.prototype.clone = function () {
  64151. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  64152. };
  64153. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  64154. // orientation of a polygon is flipped.
  64155. Vertex.prototype.flip = function () {
  64156. this.normal = this.normal.scale(-1);
  64157. };
  64158. // Create a new vertex between this vertex and `other` by linearly
  64159. // interpolating all properties using a parameter of `t`. Subclasses should
  64160. // override this to interpolate additional properties.
  64161. Vertex.prototype.interpolate = function (other, t) {
  64162. 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));
  64163. };
  64164. return Vertex;
  64165. }());
  64166. // # class Plane
  64167. // Represents a plane in 3D space.
  64168. var Plane = /** @class */ (function () {
  64169. function Plane(normal, w) {
  64170. this.normal = normal;
  64171. this.w = w;
  64172. }
  64173. Plane.FromPoints = function (a, b, c) {
  64174. var v0 = c.subtract(a);
  64175. var v1 = b.subtract(a);
  64176. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64177. return null;
  64178. }
  64179. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64180. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64181. };
  64182. Plane.prototype.clone = function () {
  64183. return new Plane(this.normal.clone(), this.w);
  64184. };
  64185. Plane.prototype.flip = function () {
  64186. this.normal.scaleInPlace(-1);
  64187. this.w = -this.w;
  64188. };
  64189. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64190. // fragments in the appropriate lists. Coplanar polygons go into either
  64191. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64192. // respect to this plane. Polygons in front or in back of this plane go into
  64193. // either `front` or `back`.
  64194. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  64195. var COPLANAR = 0;
  64196. var FRONT = 1;
  64197. var BACK = 2;
  64198. var SPANNING = 3;
  64199. // Classify each point as well as the entire polygon into one of the above
  64200. // four classes.
  64201. var polygonType = 0;
  64202. var types = [];
  64203. var i;
  64204. var t;
  64205. for (i = 0; i < polygon.vertices.length; i++) {
  64206. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  64207. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  64208. polygonType |= type;
  64209. types.push(type);
  64210. }
  64211. // Put the polygon in the correct list, splitting it when necessary.
  64212. switch (polygonType) {
  64213. case COPLANAR:
  64214. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  64215. break;
  64216. case FRONT:
  64217. front.push(polygon);
  64218. break;
  64219. case BACK:
  64220. back.push(polygon);
  64221. break;
  64222. case SPANNING:
  64223. var f = [], b = [];
  64224. for (i = 0; i < polygon.vertices.length; i++) {
  64225. var j = (i + 1) % polygon.vertices.length;
  64226. var ti = types[i], tj = types[j];
  64227. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  64228. if (ti !== BACK)
  64229. f.push(vi);
  64230. if (ti !== FRONT)
  64231. b.push(ti !== BACK ? vi.clone() : vi);
  64232. if ((ti | tj) === SPANNING) {
  64233. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  64234. var v = vi.interpolate(vj, t);
  64235. f.push(v);
  64236. b.push(v.clone());
  64237. }
  64238. }
  64239. var poly;
  64240. if (f.length >= 3) {
  64241. poly = new Polygon(f, polygon.shared);
  64242. if (poly.plane)
  64243. front.push(poly);
  64244. }
  64245. if (b.length >= 3) {
  64246. poly = new Polygon(b, polygon.shared);
  64247. if (poly.plane)
  64248. back.push(poly);
  64249. }
  64250. break;
  64251. }
  64252. };
  64253. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  64254. // point is on the plane.
  64255. Plane.EPSILON = 1e-5;
  64256. return Plane;
  64257. }());
  64258. // # class Polygon
  64259. // Represents a convex polygon. The vertices used to initialize a polygon must
  64260. // be coplanar and form a convex loop.
  64261. //
  64262. // Each convex polygon has a `shared` property, which is shared between all
  64263. // polygons that are clones of each other or were split from the same polygon.
  64264. // This can be used to define per-polygon properties (such as surface color).
  64265. var Polygon = /** @class */ (function () {
  64266. function Polygon(vertices, shared) {
  64267. this.vertices = vertices;
  64268. this.shared = shared;
  64269. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  64270. }
  64271. Polygon.prototype.clone = function () {
  64272. var vertices = this.vertices.map(function (v) { return v.clone(); });
  64273. return new Polygon(vertices, this.shared);
  64274. };
  64275. Polygon.prototype.flip = function () {
  64276. this.vertices.reverse().map(function (v) { v.flip(); });
  64277. this.plane.flip();
  64278. };
  64279. return Polygon;
  64280. }());
  64281. // # class Node
  64282. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  64283. // by picking a polygon to split along. That polygon (and all other coplanar
  64284. // polygons) are added directly to that node and the other polygons are added to
  64285. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  64286. // no distinction between internal and leaf nodes.
  64287. var Node = /** @class */ (function () {
  64288. function Node(polygons) {
  64289. this.plane = null;
  64290. this.front = null;
  64291. this.back = null;
  64292. this.polygons = new Array();
  64293. if (polygons) {
  64294. this.build(polygons);
  64295. }
  64296. }
  64297. Node.prototype.clone = function () {
  64298. var node = new Node();
  64299. node.plane = this.plane && this.plane.clone();
  64300. node.front = this.front && this.front.clone();
  64301. node.back = this.back && this.back.clone();
  64302. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  64303. return node;
  64304. };
  64305. // Convert solid space to empty space and empty space to solid space.
  64306. Node.prototype.invert = function () {
  64307. for (var i = 0; i < this.polygons.length; i++) {
  64308. this.polygons[i].flip();
  64309. }
  64310. if (this.plane) {
  64311. this.plane.flip();
  64312. }
  64313. if (this.front) {
  64314. this.front.invert();
  64315. }
  64316. if (this.back) {
  64317. this.back.invert();
  64318. }
  64319. var temp = this.front;
  64320. this.front = this.back;
  64321. this.back = temp;
  64322. };
  64323. // Recursively remove all polygons in `polygons` that are inside this BSP
  64324. // tree.
  64325. Node.prototype.clipPolygons = function (polygons) {
  64326. if (!this.plane)
  64327. return polygons.slice();
  64328. var front = new Array(), back = new Array();
  64329. for (var i = 0; i < polygons.length; i++) {
  64330. this.plane.splitPolygon(polygons[i], front, back, front, back);
  64331. }
  64332. if (this.front) {
  64333. front = this.front.clipPolygons(front);
  64334. }
  64335. if (this.back) {
  64336. back = this.back.clipPolygons(back);
  64337. }
  64338. else {
  64339. back = [];
  64340. }
  64341. return front.concat(back);
  64342. };
  64343. // Remove all polygons in this BSP tree that are inside the other BSP tree
  64344. // `bsp`.
  64345. Node.prototype.clipTo = function (bsp) {
  64346. this.polygons = bsp.clipPolygons(this.polygons);
  64347. if (this.front)
  64348. this.front.clipTo(bsp);
  64349. if (this.back)
  64350. this.back.clipTo(bsp);
  64351. };
  64352. // Return a list of all polygons in this BSP tree.
  64353. Node.prototype.allPolygons = function () {
  64354. var polygons = this.polygons.slice();
  64355. if (this.front)
  64356. polygons = polygons.concat(this.front.allPolygons());
  64357. if (this.back)
  64358. polygons = polygons.concat(this.back.allPolygons());
  64359. return polygons;
  64360. };
  64361. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  64362. // new polygons are filtered down to the bottom of the tree and become new
  64363. // nodes there. Each set of polygons is partitioned using the first polygon
  64364. // (no heuristic is used to pick a good split).
  64365. Node.prototype.build = function (polygons) {
  64366. if (!polygons.length)
  64367. return;
  64368. if (!this.plane)
  64369. this.plane = polygons[0].plane.clone();
  64370. var front = new Array(), back = new Array();
  64371. for (var i = 0; i < polygons.length; i++) {
  64372. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  64373. }
  64374. if (front.length) {
  64375. if (!this.front)
  64376. this.front = new Node();
  64377. this.front.build(front);
  64378. }
  64379. if (back.length) {
  64380. if (!this.back)
  64381. this.back = new Node();
  64382. this.back.build(back);
  64383. }
  64384. };
  64385. return Node;
  64386. }());
  64387. var CSG = /** @class */ (function () {
  64388. function CSG() {
  64389. this.polygons = new Array();
  64390. }
  64391. // Convert BABYLON.Mesh to BABYLON.CSG
  64392. CSG.FromMesh = function (mesh) {
  64393. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  64394. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  64395. if (mesh instanceof BABYLON.Mesh) {
  64396. mesh.computeWorldMatrix(true);
  64397. matrix = mesh.getWorldMatrix();
  64398. meshPosition = mesh.position.clone();
  64399. meshRotation = mesh.rotation.clone();
  64400. if (mesh.rotationQuaternion) {
  64401. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  64402. }
  64403. meshScaling = mesh.scaling.clone();
  64404. }
  64405. else {
  64406. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  64407. }
  64408. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64409. var subMeshes = mesh.subMeshes;
  64410. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  64411. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  64412. vertices = [];
  64413. for (var j = 0; j < 3; j++) {
  64414. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  64415. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  64416. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  64417. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  64418. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  64419. vertex = new Vertex(position, normal, uv);
  64420. vertices.push(vertex);
  64421. }
  64422. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  64423. // To handle the case of degenerated triangle
  64424. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  64425. if (polygon.plane)
  64426. polygons.push(polygon);
  64427. }
  64428. }
  64429. var csg = CSG.FromPolygons(polygons);
  64430. csg.matrix = matrix;
  64431. csg.position = meshPosition;
  64432. csg.rotation = meshRotation;
  64433. csg.scaling = meshScaling;
  64434. csg.rotationQuaternion = meshRotationQuaternion;
  64435. currentCSGMeshId++;
  64436. return csg;
  64437. };
  64438. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  64439. CSG.FromPolygons = function (polygons) {
  64440. var csg = new CSG();
  64441. csg.polygons = polygons;
  64442. return csg;
  64443. };
  64444. CSG.prototype.clone = function () {
  64445. var csg = new CSG();
  64446. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  64447. csg.copyTransformAttributes(this);
  64448. return csg;
  64449. };
  64450. CSG.prototype.union = function (csg) {
  64451. var a = new Node(this.clone().polygons);
  64452. var b = new Node(csg.clone().polygons);
  64453. a.clipTo(b);
  64454. b.clipTo(a);
  64455. b.invert();
  64456. b.clipTo(a);
  64457. b.invert();
  64458. a.build(b.allPolygons());
  64459. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64460. };
  64461. CSG.prototype.unionInPlace = function (csg) {
  64462. var a = new Node(this.polygons);
  64463. var b = new Node(csg.polygons);
  64464. a.clipTo(b);
  64465. b.clipTo(a);
  64466. b.invert();
  64467. b.clipTo(a);
  64468. b.invert();
  64469. a.build(b.allPolygons());
  64470. this.polygons = a.allPolygons();
  64471. };
  64472. CSG.prototype.subtract = function (csg) {
  64473. var a = new Node(this.clone().polygons);
  64474. var b = new Node(csg.clone().polygons);
  64475. a.invert();
  64476. a.clipTo(b);
  64477. b.clipTo(a);
  64478. b.invert();
  64479. b.clipTo(a);
  64480. b.invert();
  64481. a.build(b.allPolygons());
  64482. a.invert();
  64483. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64484. };
  64485. CSG.prototype.subtractInPlace = function (csg) {
  64486. var a = new Node(this.polygons);
  64487. var b = new Node(csg.polygons);
  64488. a.invert();
  64489. a.clipTo(b);
  64490. b.clipTo(a);
  64491. b.invert();
  64492. b.clipTo(a);
  64493. b.invert();
  64494. a.build(b.allPolygons());
  64495. a.invert();
  64496. this.polygons = a.allPolygons();
  64497. };
  64498. CSG.prototype.intersect = function (csg) {
  64499. var a = new Node(this.clone().polygons);
  64500. var b = new Node(csg.clone().polygons);
  64501. a.invert();
  64502. b.clipTo(a);
  64503. b.invert();
  64504. a.clipTo(b);
  64505. b.clipTo(a);
  64506. a.build(b.allPolygons());
  64507. a.invert();
  64508. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64509. };
  64510. CSG.prototype.intersectInPlace = function (csg) {
  64511. var a = new Node(this.polygons);
  64512. var b = new Node(csg.polygons);
  64513. a.invert();
  64514. b.clipTo(a);
  64515. b.invert();
  64516. a.clipTo(b);
  64517. b.clipTo(a);
  64518. a.build(b.allPolygons());
  64519. a.invert();
  64520. this.polygons = a.allPolygons();
  64521. };
  64522. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  64523. // not modified.
  64524. CSG.prototype.inverse = function () {
  64525. var csg = this.clone();
  64526. csg.inverseInPlace();
  64527. return csg;
  64528. };
  64529. CSG.prototype.inverseInPlace = function () {
  64530. this.polygons.map(function (p) { p.flip(); });
  64531. };
  64532. // This is used to keep meshes transformations so they can be restored
  64533. // when we build back a Babylon Mesh
  64534. // NB : All CSG operations are performed in world coordinates
  64535. CSG.prototype.copyTransformAttributes = function (csg) {
  64536. this.matrix = csg.matrix;
  64537. this.position = csg.position;
  64538. this.rotation = csg.rotation;
  64539. this.scaling = csg.scaling;
  64540. this.rotationQuaternion = csg.rotationQuaternion;
  64541. return this;
  64542. };
  64543. // Build Raw mesh from CSG
  64544. // Coordinates here are in world space
  64545. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  64546. var matrix = this.matrix.clone();
  64547. matrix.invert();
  64548. 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;
  64549. if (keepSubMeshes) {
  64550. // Sort Polygons, since subMeshes are indices range
  64551. polygons.sort(function (a, b) {
  64552. if (a.shared.meshId === b.shared.meshId) {
  64553. return a.shared.subMeshId - b.shared.subMeshId;
  64554. }
  64555. else {
  64556. return a.shared.meshId - b.shared.meshId;
  64557. }
  64558. });
  64559. }
  64560. for (var i = 0, il = polygons.length; i < il; i++) {
  64561. polygon = polygons[i];
  64562. // Building SubMeshes
  64563. if (!subMesh_dict[polygon.shared.meshId]) {
  64564. subMesh_dict[polygon.shared.meshId] = {};
  64565. }
  64566. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  64567. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  64568. indexStart: +Infinity,
  64569. indexEnd: -Infinity,
  64570. materialIndex: polygon.shared.materialIndex
  64571. };
  64572. }
  64573. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  64574. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  64575. polygonIndices[0] = 0;
  64576. polygonIndices[1] = j - 1;
  64577. polygonIndices[2] = j;
  64578. for (var k = 0; k < 3; k++) {
  64579. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  64580. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  64581. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  64582. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  64583. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  64584. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  64585. // Check if 2 points can be merged
  64586. if (!(typeof vertex_idx !== 'undefined' &&
  64587. normals[vertex_idx * 3] === localNormal.x &&
  64588. normals[vertex_idx * 3 + 1] === localNormal.y &&
  64589. normals[vertex_idx * 3 + 2] === localNormal.z &&
  64590. uvs[vertex_idx * 2] === uv.x &&
  64591. uvs[vertex_idx * 2 + 1] === uv.y)) {
  64592. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  64593. uvs.push(uv.x, uv.y);
  64594. normals.push(normal.x, normal.y, normal.z);
  64595. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  64596. }
  64597. indices.push(vertex_idx);
  64598. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  64599. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  64600. currentIndex++;
  64601. }
  64602. }
  64603. }
  64604. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  64605. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  64606. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  64607. mesh.setIndices(indices, null);
  64608. if (keepSubMeshes) {
  64609. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  64610. var materialIndexOffset = 0, materialMaxIndex;
  64611. mesh.subMeshes = new Array();
  64612. for (var m in subMesh_dict) {
  64613. materialMaxIndex = -1;
  64614. for (var sm in subMesh_dict[m]) {
  64615. subMesh_obj = subMesh_dict[m][sm];
  64616. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  64617. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  64618. }
  64619. materialIndexOffset += ++materialMaxIndex;
  64620. }
  64621. }
  64622. return mesh;
  64623. };
  64624. // Build Mesh from CSG taking material and transforms into account
  64625. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  64626. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  64627. mesh.material = material;
  64628. mesh.position.copyFrom(this.position);
  64629. mesh.rotation.copyFrom(this.rotation);
  64630. if (this.rotationQuaternion) {
  64631. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  64632. }
  64633. mesh.scaling.copyFrom(this.scaling);
  64634. mesh.computeWorldMatrix(true);
  64635. return mesh;
  64636. };
  64637. return CSG;
  64638. }());
  64639. BABYLON.CSG = CSG;
  64640. })(BABYLON || (BABYLON = {}));
  64641. //# sourceMappingURL=babylon.csg.js.map
  64642. var BABYLON;
  64643. (function (BABYLON) {
  64644. var LensFlare = /** @class */ (function () {
  64645. function LensFlare(size, position, color, imgUrl, system) {
  64646. this.size = size;
  64647. this.position = position;
  64648. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  64649. this.color = color || new BABYLON.Color3(1, 1, 1);
  64650. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  64651. this._system = system;
  64652. system.lensFlares.push(this);
  64653. }
  64654. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  64655. return new LensFlare(size, position, color, imgUrl, system);
  64656. };
  64657. LensFlare.prototype.dispose = function () {
  64658. if (this.texture) {
  64659. this.texture.dispose();
  64660. }
  64661. // Remove from scene
  64662. var index = this._system.lensFlares.indexOf(this);
  64663. this._system.lensFlares.splice(index, 1);
  64664. };
  64665. ;
  64666. return LensFlare;
  64667. }());
  64668. BABYLON.LensFlare = LensFlare;
  64669. })(BABYLON || (BABYLON = {}));
  64670. //# sourceMappingURL=babylon.lensFlare.js.map
  64671. var BABYLON;
  64672. (function (BABYLON) {
  64673. var LensFlareSystem = /** @class */ (function () {
  64674. function LensFlareSystem(name, emitter, scene) {
  64675. this.name = name;
  64676. this.lensFlares = new Array();
  64677. this.borderLimit = 300;
  64678. this.viewportBorder = 0;
  64679. this.layerMask = 0x0FFFFFFF;
  64680. this._vertexBuffers = {};
  64681. this._isEnabled = true;
  64682. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64683. this._emitter = emitter;
  64684. this.id = name;
  64685. scene.lensFlareSystems.push(this);
  64686. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  64687. var engine = scene.getEngine();
  64688. // VBO
  64689. var vertices = [];
  64690. vertices.push(1, 1);
  64691. vertices.push(-1, 1);
  64692. vertices.push(-1, -1);
  64693. vertices.push(1, -1);
  64694. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64695. // Indices
  64696. var indices = [];
  64697. indices.push(0);
  64698. indices.push(1);
  64699. indices.push(2);
  64700. indices.push(0);
  64701. indices.push(2);
  64702. indices.push(3);
  64703. this._indexBuffer = engine.createIndexBuffer(indices);
  64704. // Effects
  64705. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  64706. }
  64707. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  64708. get: function () {
  64709. return this._isEnabled;
  64710. },
  64711. set: function (value) {
  64712. this._isEnabled = value;
  64713. },
  64714. enumerable: true,
  64715. configurable: true
  64716. });
  64717. LensFlareSystem.prototype.getScene = function () {
  64718. return this._scene;
  64719. };
  64720. LensFlareSystem.prototype.getEmitter = function () {
  64721. return this._emitter;
  64722. };
  64723. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  64724. this._emitter = newEmitter;
  64725. };
  64726. LensFlareSystem.prototype.getEmitterPosition = function () {
  64727. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  64728. };
  64729. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  64730. var position = this.getEmitterPosition();
  64731. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  64732. this._positionX = position.x;
  64733. this._positionY = position.y;
  64734. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  64735. if (this.viewportBorder > 0) {
  64736. globalViewport.x -= this.viewportBorder;
  64737. globalViewport.y -= this.viewportBorder;
  64738. globalViewport.width += this.viewportBorder * 2;
  64739. globalViewport.height += this.viewportBorder * 2;
  64740. position.x += this.viewportBorder;
  64741. position.y += this.viewportBorder;
  64742. this._positionX += this.viewportBorder;
  64743. this._positionY += this.viewportBorder;
  64744. }
  64745. if (position.z > 0) {
  64746. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  64747. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  64748. return true;
  64749. }
  64750. return true;
  64751. }
  64752. return false;
  64753. };
  64754. LensFlareSystem.prototype._isVisible = function () {
  64755. if (!this._isEnabled || !this._scene.activeCamera) {
  64756. return false;
  64757. }
  64758. var emitterPosition = this.getEmitterPosition();
  64759. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  64760. var distance = direction.length();
  64761. direction.normalize();
  64762. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  64763. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  64764. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  64765. };
  64766. LensFlareSystem.prototype.render = function () {
  64767. if (!this._effect.isReady() || !this._scene.activeCamera)
  64768. return false;
  64769. var engine = this._scene.getEngine();
  64770. var viewport = this._scene.activeCamera.viewport;
  64771. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  64772. // Position
  64773. if (!this.computeEffectivePosition(globalViewport)) {
  64774. return false;
  64775. }
  64776. // Visibility
  64777. if (!this._isVisible()) {
  64778. return false;
  64779. }
  64780. // Intensity
  64781. var awayX;
  64782. var awayY;
  64783. if (this._positionX < this.borderLimit + globalViewport.x) {
  64784. awayX = this.borderLimit + globalViewport.x - this._positionX;
  64785. }
  64786. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  64787. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  64788. }
  64789. else {
  64790. awayX = 0;
  64791. }
  64792. if (this._positionY < this.borderLimit + globalViewport.y) {
  64793. awayY = this.borderLimit + globalViewport.y - this._positionY;
  64794. }
  64795. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  64796. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  64797. }
  64798. else {
  64799. awayY = 0;
  64800. }
  64801. var away = (awayX > awayY) ? awayX : awayY;
  64802. away -= this.viewportBorder;
  64803. if (away > this.borderLimit) {
  64804. away = this.borderLimit;
  64805. }
  64806. var intensity = 1.0 - (away / this.borderLimit);
  64807. if (intensity < 0) {
  64808. return false;
  64809. }
  64810. if (intensity > 1.0) {
  64811. intensity = 1.0;
  64812. }
  64813. if (this.viewportBorder > 0) {
  64814. globalViewport.x += this.viewportBorder;
  64815. globalViewport.y += this.viewportBorder;
  64816. globalViewport.width -= this.viewportBorder * 2;
  64817. globalViewport.height -= this.viewportBorder * 2;
  64818. this._positionX -= this.viewportBorder;
  64819. this._positionY -= this.viewportBorder;
  64820. }
  64821. // Position
  64822. var centerX = globalViewport.x + globalViewport.width / 2;
  64823. var centerY = globalViewport.y + globalViewport.height / 2;
  64824. var distX = centerX - this._positionX;
  64825. var distY = centerY - this._positionY;
  64826. // Effects
  64827. engine.enableEffect(this._effect);
  64828. engine.setState(false);
  64829. engine.setDepthBuffer(false);
  64830. // VBOs
  64831. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64832. // Flares
  64833. for (var index = 0; index < this.lensFlares.length; index++) {
  64834. var flare = this.lensFlares[index];
  64835. engine.setAlphaMode(flare.alphaMode);
  64836. var x = centerX - (distX * flare.position);
  64837. var y = centerY - (distY * flare.position);
  64838. var cw = flare.size;
  64839. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  64840. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  64841. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  64842. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  64843. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  64844. // Texture
  64845. this._effect.setTexture("textureSampler", flare.texture);
  64846. // Color
  64847. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  64848. // Draw order
  64849. engine.draw(true, 0, 6);
  64850. }
  64851. engine.setDepthBuffer(true);
  64852. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64853. return true;
  64854. };
  64855. LensFlareSystem.prototype.dispose = function () {
  64856. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64857. if (vertexBuffer) {
  64858. vertexBuffer.dispose();
  64859. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64860. }
  64861. if (this._indexBuffer) {
  64862. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64863. this._indexBuffer = null;
  64864. }
  64865. while (this.lensFlares.length) {
  64866. this.lensFlares[0].dispose();
  64867. }
  64868. // Remove from scene
  64869. var index = this._scene.lensFlareSystems.indexOf(this);
  64870. this._scene.lensFlareSystems.splice(index, 1);
  64871. };
  64872. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  64873. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  64874. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  64875. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  64876. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  64877. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  64878. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  64879. var parsedFlare = parsedLensFlareSystem.flares[index];
  64880. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  64881. }
  64882. return lensFlareSystem;
  64883. };
  64884. LensFlareSystem.prototype.serialize = function () {
  64885. var serializationObject = {};
  64886. serializationObject.id = this.id;
  64887. serializationObject.name = this.name;
  64888. serializationObject.emitterId = this.getEmitter().id;
  64889. serializationObject.borderLimit = this.borderLimit;
  64890. serializationObject.flares = [];
  64891. for (var index = 0; index < this.lensFlares.length; index++) {
  64892. var flare = this.lensFlares[index];
  64893. serializationObject.flares.push({
  64894. size: flare.size,
  64895. position: flare.position,
  64896. color: flare.color.asArray(),
  64897. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  64898. });
  64899. }
  64900. return serializationObject;
  64901. };
  64902. return LensFlareSystem;
  64903. }());
  64904. BABYLON.LensFlareSystem = LensFlareSystem;
  64905. })(BABYLON || (BABYLON = {}));
  64906. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  64907. var BABYLON;
  64908. (function (BABYLON) {
  64909. /**
  64910. * This is a holder class for the physics joint created by the physics plugin.
  64911. * It holds a set of functions to control the underlying joint.
  64912. */
  64913. var PhysicsJoint = /** @class */ (function () {
  64914. function PhysicsJoint(type, jointData) {
  64915. this.type = type;
  64916. this.jointData = jointData;
  64917. jointData.nativeParams = jointData.nativeParams || {};
  64918. }
  64919. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  64920. get: function () {
  64921. return this._physicsJoint;
  64922. },
  64923. set: function (newJoint) {
  64924. if (this._physicsJoint) {
  64925. //remove from the wolrd
  64926. }
  64927. this._physicsJoint = newJoint;
  64928. },
  64929. enumerable: true,
  64930. configurable: true
  64931. });
  64932. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  64933. set: function (physicsPlugin) {
  64934. this._physicsPlugin = physicsPlugin;
  64935. },
  64936. enumerable: true,
  64937. configurable: true
  64938. });
  64939. /**
  64940. * Execute a function that is physics-plugin specific.
  64941. * @param {Function} func the function that will be executed.
  64942. * It accepts two parameters: the physics world and the physics joint.
  64943. */
  64944. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  64945. func(this._physicsPlugin.world, this._physicsJoint);
  64946. };
  64947. //TODO check if the native joints are the same
  64948. //Joint Types
  64949. PhysicsJoint.DistanceJoint = 0;
  64950. PhysicsJoint.HingeJoint = 1;
  64951. PhysicsJoint.BallAndSocketJoint = 2;
  64952. PhysicsJoint.WheelJoint = 3;
  64953. PhysicsJoint.SliderJoint = 4;
  64954. //OIMO
  64955. PhysicsJoint.PrismaticJoint = 5;
  64956. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  64957. PhysicsJoint.UniversalJoint = 6;
  64958. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  64959. //Cannon
  64960. //Similar to a Ball-Joint. Different in params
  64961. PhysicsJoint.PointToPointJoint = 8;
  64962. //Cannon only at the moment
  64963. PhysicsJoint.SpringJoint = 9;
  64964. PhysicsJoint.LockJoint = 10;
  64965. return PhysicsJoint;
  64966. }());
  64967. BABYLON.PhysicsJoint = PhysicsJoint;
  64968. /**
  64969. * A class representing a physics distance joint.
  64970. */
  64971. var DistanceJoint = /** @class */ (function (_super) {
  64972. __extends(DistanceJoint, _super);
  64973. function DistanceJoint(jointData) {
  64974. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  64975. }
  64976. /**
  64977. * Update the predefined distance.
  64978. */
  64979. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  64980. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  64981. };
  64982. return DistanceJoint;
  64983. }(PhysicsJoint));
  64984. BABYLON.DistanceJoint = DistanceJoint;
  64985. var MotorEnabledJoint = /** @class */ (function (_super) {
  64986. __extends(MotorEnabledJoint, _super);
  64987. function MotorEnabledJoint(type, jointData) {
  64988. return _super.call(this, type, jointData) || this;
  64989. }
  64990. /**
  64991. * Set the motor values.
  64992. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64993. * @param {number} force the force to apply
  64994. * @param {number} maxForce max force for this motor.
  64995. */
  64996. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  64997. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  64998. };
  64999. /**
  65000. * Set the motor's limits.
  65001. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65002. */
  65003. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65004. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65005. };
  65006. return MotorEnabledJoint;
  65007. }(PhysicsJoint));
  65008. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  65009. /**
  65010. * This class represents a single hinge physics joint
  65011. */
  65012. var HingeJoint = /** @class */ (function (_super) {
  65013. __extends(HingeJoint, _super);
  65014. function HingeJoint(jointData) {
  65015. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  65016. }
  65017. /**
  65018. * Set the motor values.
  65019. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65020. * @param {number} force the force to apply
  65021. * @param {number} maxForce max force for this motor.
  65022. */
  65023. HingeJoint.prototype.setMotor = function (force, maxForce) {
  65024. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65025. };
  65026. /**
  65027. * Set the motor's limits.
  65028. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65029. */
  65030. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65031. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65032. };
  65033. return HingeJoint;
  65034. }(MotorEnabledJoint));
  65035. BABYLON.HingeJoint = HingeJoint;
  65036. /**
  65037. * This class represents a dual hinge physics joint (same as wheel joint)
  65038. */
  65039. var Hinge2Joint = /** @class */ (function (_super) {
  65040. __extends(Hinge2Joint, _super);
  65041. function Hinge2Joint(jointData) {
  65042. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  65043. }
  65044. /**
  65045. * Set the motor values.
  65046. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65047. * @param {number} force the force to apply
  65048. * @param {number} maxForce max force for this motor.
  65049. * @param {motorIndex} the motor's index, 0 or 1.
  65050. */
  65051. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  65052. if (motorIndex === void 0) { motorIndex = 0; }
  65053. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  65054. };
  65055. /**
  65056. * Set the motor limits.
  65057. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65058. * @param {number} upperLimit the upper limit
  65059. * @param {number} lowerLimit lower limit
  65060. * @param {motorIndex} the motor's index, 0 or 1.
  65061. */
  65062. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  65063. if (motorIndex === void 0) { motorIndex = 0; }
  65064. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  65065. };
  65066. return Hinge2Joint;
  65067. }(MotorEnabledJoint));
  65068. BABYLON.Hinge2Joint = Hinge2Joint;
  65069. })(BABYLON || (BABYLON = {}));
  65070. //# sourceMappingURL=babylon.physicsJoint.js.map
  65071. var BABYLON;
  65072. (function (BABYLON) {
  65073. var PhysicsImpostor = /** @class */ (function () {
  65074. function PhysicsImpostor(object, type, _options, _scene) {
  65075. if (_options === void 0) { _options = { mass: 0 }; }
  65076. var _this = this;
  65077. this.object = object;
  65078. this.type = type;
  65079. this._options = _options;
  65080. this._scene = _scene;
  65081. this._bodyUpdateRequired = false;
  65082. this._onBeforePhysicsStepCallbacks = new Array();
  65083. this._onAfterPhysicsStepCallbacks = new Array();
  65084. this._onPhysicsCollideCallbacks = [];
  65085. this._deltaPosition = BABYLON.Vector3.Zero();
  65086. this._isDisposed = false;
  65087. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  65088. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  65089. /**
  65090. * this function is executed by the physics engine.
  65091. */
  65092. this.beforeStep = function () {
  65093. if (!_this._physicsEngine) {
  65094. return;
  65095. }
  65096. if (_this._options.ignoreParent && _this.object.parent) {
  65097. _this._tmpPositionWithDelta.copyFrom(_this.object.getAbsolutePosition());
  65098. //this.object.getAbsolutePosition().subtractToRef(this._deltaPosition, this._tmpPositionWithDelta);
  65099. }
  65100. else {
  65101. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  65102. }
  65103. //conjugate deltaRotation
  65104. if (_this.object.rotationQuaternion) {
  65105. if (_this._deltaRotationConjugated) {
  65106. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  65107. }
  65108. else {
  65109. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  65110. }
  65111. }
  65112. // Only if not disabled
  65113. if (!_this._options.disableBidirectionalTransformation) {
  65114. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  65115. }
  65116. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  65117. func(_this);
  65118. });
  65119. };
  65120. /**
  65121. * this function is executed by the physics engine.
  65122. */
  65123. this.afterStep = function () {
  65124. if (!_this._physicsEngine) {
  65125. return;
  65126. }
  65127. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  65128. func(_this);
  65129. });
  65130. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  65131. if (_this._options.ignoreParent && _this.object.parent) {
  65132. _this.object.position.subtractInPlace(_this.object.parent.getAbsolutePosition());
  65133. }
  65134. else {
  65135. _this.object.position.addInPlace(_this._deltaPosition);
  65136. }
  65137. if (_this._deltaRotation && _this.object.rotationQuaternion) {
  65138. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  65139. }
  65140. };
  65141. /**
  65142. * Legacy collision detection event support
  65143. */
  65144. this.onCollideEvent = null;
  65145. //event and body object due to cannon's event-based architecture.
  65146. this.onCollide = function (e) {
  65147. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  65148. return;
  65149. }
  65150. if (!_this._physicsEngine) {
  65151. return;
  65152. }
  65153. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  65154. if (otherImpostor) {
  65155. // Legacy collision detection event support
  65156. if (_this.onCollideEvent) {
  65157. _this.onCollideEvent(_this, otherImpostor);
  65158. }
  65159. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  65160. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  65161. }).forEach(function (obj) {
  65162. obj.callback(_this, otherImpostor);
  65163. });
  65164. }
  65165. };
  65166. //sanity check!
  65167. if (!this.object) {
  65168. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65169. return;
  65170. }
  65171. //legacy support for old syntax.
  65172. if (!this._scene && object.getScene) {
  65173. this._scene = object.getScene();
  65174. }
  65175. if (!this._scene) {
  65176. return;
  65177. }
  65178. this._physicsEngine = this._scene.getPhysicsEngine();
  65179. if (!this._physicsEngine) {
  65180. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65181. }
  65182. else {
  65183. //set the object's quaternion, if not set
  65184. if (!this.object.rotationQuaternion) {
  65185. if (this.object.rotation) {
  65186. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65187. }
  65188. else {
  65189. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65190. }
  65191. }
  65192. //default options params
  65193. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65194. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65195. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65196. this._joints = [];
  65197. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  65198. if (!this.object.parent || this._options.ignoreParent) {
  65199. this._init();
  65200. }
  65201. else if (this.object.parent.physicsImpostor) {
  65202. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  65203. }
  65204. }
  65205. }
  65206. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  65207. get: function () {
  65208. return this._isDisposed;
  65209. },
  65210. enumerable: true,
  65211. configurable: true
  65212. });
  65213. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  65214. get: function () {
  65215. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  65216. },
  65217. set: function (value) {
  65218. this.setMass(value);
  65219. },
  65220. enumerable: true,
  65221. configurable: true
  65222. });
  65223. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  65224. get: function () {
  65225. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  65226. },
  65227. set: function (value) {
  65228. if (!this._physicsEngine) {
  65229. return;
  65230. }
  65231. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  65232. },
  65233. enumerable: true,
  65234. configurable: true
  65235. });
  65236. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  65237. get: function () {
  65238. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  65239. },
  65240. set: function (value) {
  65241. if (!this._physicsEngine) {
  65242. return;
  65243. }
  65244. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  65245. },
  65246. enumerable: true,
  65247. configurable: true
  65248. });
  65249. /**
  65250. * This function will completly initialize this impostor.
  65251. * It will create a new body - but only if this mesh has no parent.
  65252. * If it has, this impostor will not be used other than to define the impostor
  65253. * of the child mesh.
  65254. */
  65255. PhysicsImpostor.prototype._init = function () {
  65256. if (!this._physicsEngine) {
  65257. return;
  65258. }
  65259. this._physicsEngine.removeImpostor(this);
  65260. this.physicsBody = null;
  65261. this._parent = this._parent || this._getPhysicsParent();
  65262. if (!this.parent || this._options.ignoreParent) {
  65263. this._physicsEngine.addImpostor(this);
  65264. }
  65265. };
  65266. PhysicsImpostor.prototype._getPhysicsParent = function () {
  65267. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  65268. var parentMesh = this.object.parent;
  65269. return parentMesh.physicsImpostor;
  65270. }
  65271. return null;
  65272. };
  65273. /**
  65274. * Should a new body be generated.
  65275. */
  65276. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  65277. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  65278. };
  65279. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  65280. this.forceUpdate();
  65281. };
  65282. /**
  65283. * Force a regeneration of this or the parent's impostor's body.
  65284. * Use under cautious - This will remove all joints already implemented.
  65285. */
  65286. PhysicsImpostor.prototype.forceUpdate = function () {
  65287. this._init();
  65288. if (this.parent && !this._options.ignoreParent) {
  65289. this.parent.forceUpdate();
  65290. }
  65291. };
  65292. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  65293. /*public get mesh(): AbstractMesh {
  65294. return this._mesh;
  65295. }*/
  65296. /**
  65297. * Gets the body that holds this impostor. Either its own, or its parent.
  65298. */
  65299. get: function () {
  65300. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  65301. },
  65302. /**
  65303. * Set the physics body. Used mainly by the physics engine/plugin
  65304. */
  65305. set: function (physicsBody) {
  65306. if (this._physicsBody && this._physicsEngine) {
  65307. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  65308. }
  65309. this._physicsBody = physicsBody;
  65310. this.resetUpdateFlags();
  65311. },
  65312. enumerable: true,
  65313. configurable: true
  65314. });
  65315. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  65316. get: function () {
  65317. return !this._options.ignoreParent && this._parent ? this._parent : null;
  65318. },
  65319. set: function (value) {
  65320. this._parent = value;
  65321. },
  65322. enumerable: true,
  65323. configurable: true
  65324. });
  65325. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  65326. this._bodyUpdateRequired = false;
  65327. };
  65328. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  65329. if (this.object.getBoundingInfo) {
  65330. var q = this.object.rotationQuaternion;
  65331. //reset rotation
  65332. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  65333. //calculate the world matrix with no rotation
  65334. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65335. var boundingInfo = this.object.getBoundingInfo();
  65336. var size = void 0;
  65337. if (boundingInfo) {
  65338. size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  65339. }
  65340. else {
  65341. size = BABYLON.Vector3.Zero();
  65342. }
  65343. //bring back the rotation
  65344. this.object.rotationQuaternion = q;
  65345. //calculate the world matrix with the new rotation
  65346. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65347. return size;
  65348. }
  65349. else {
  65350. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  65351. }
  65352. };
  65353. PhysicsImpostor.prototype.getObjectCenter = function () {
  65354. if (this.object.getBoundingInfo) {
  65355. var boundingInfo = this.object.getBoundingInfo();
  65356. if (!boundingInfo) {
  65357. return this.object.position;
  65358. }
  65359. return boundingInfo.boundingBox.centerWorld;
  65360. }
  65361. else {
  65362. return this.object.position;
  65363. }
  65364. };
  65365. /**
  65366. * Get a specific parametes from the options parameter.
  65367. */
  65368. PhysicsImpostor.prototype.getParam = function (paramName) {
  65369. return this._options[paramName];
  65370. };
  65371. /**
  65372. * Sets a specific parameter in the options given to the physics plugin
  65373. */
  65374. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  65375. this._options[paramName] = value;
  65376. this._bodyUpdateRequired = true;
  65377. };
  65378. /**
  65379. * Specifically change the body's mass option. Won't recreate the physics body object
  65380. */
  65381. PhysicsImpostor.prototype.setMass = function (mass) {
  65382. if (this.getParam("mass") !== mass) {
  65383. this.setParam("mass", mass);
  65384. }
  65385. if (this._physicsEngine) {
  65386. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  65387. }
  65388. };
  65389. PhysicsImpostor.prototype.getLinearVelocity = function () {
  65390. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  65391. };
  65392. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  65393. if (this._physicsEngine) {
  65394. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  65395. }
  65396. };
  65397. PhysicsImpostor.prototype.getAngularVelocity = function () {
  65398. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  65399. };
  65400. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  65401. if (this._physicsEngine) {
  65402. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  65403. }
  65404. };
  65405. /**
  65406. * Execute a function with the physics plugin native code.
  65407. * Provide a function the will have two variables - the world object and the physics body object.
  65408. */
  65409. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  65410. if (this._physicsEngine) {
  65411. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  65412. }
  65413. };
  65414. /**
  65415. * Register a function that will be executed before the physics world is stepping forward.
  65416. */
  65417. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  65418. this._onBeforePhysicsStepCallbacks.push(func);
  65419. };
  65420. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  65421. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  65422. if (index > -1) {
  65423. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  65424. }
  65425. else {
  65426. BABYLON.Tools.Warn("Function to remove was not found");
  65427. }
  65428. };
  65429. /**
  65430. * Register a function that will be executed after the physics step
  65431. */
  65432. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  65433. this._onAfterPhysicsStepCallbacks.push(func);
  65434. };
  65435. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  65436. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  65437. if (index > -1) {
  65438. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  65439. }
  65440. else {
  65441. BABYLON.Tools.Warn("Function to remove was not found");
  65442. }
  65443. };
  65444. /**
  65445. * register a function that will be executed when this impostor collides against a different body.
  65446. */
  65447. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  65448. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65449. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  65450. };
  65451. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  65452. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65453. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  65454. if (index > -1) {
  65455. this._onPhysicsCollideCallbacks.splice(index, 1);
  65456. }
  65457. else {
  65458. BABYLON.Tools.Warn("Function to remove was not found");
  65459. }
  65460. };
  65461. /**
  65462. * Apply a force
  65463. */
  65464. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  65465. if (this._physicsEngine) {
  65466. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  65467. }
  65468. return this;
  65469. };
  65470. /**
  65471. * Apply an impulse
  65472. */
  65473. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  65474. if (this._physicsEngine) {
  65475. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  65476. }
  65477. return this;
  65478. };
  65479. /**
  65480. * A help function to create a joint.
  65481. */
  65482. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  65483. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  65484. this.addJoint(otherImpostor, joint);
  65485. return this;
  65486. };
  65487. /**
  65488. * Add a joint to this impostor with a different impostor.
  65489. */
  65490. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  65491. this._joints.push({
  65492. otherImpostor: otherImpostor,
  65493. joint: joint
  65494. });
  65495. if (this._physicsEngine) {
  65496. this._physicsEngine.addJoint(this, otherImpostor, joint);
  65497. }
  65498. return this;
  65499. };
  65500. /**
  65501. * Will keep this body still, in a sleep mode.
  65502. */
  65503. PhysicsImpostor.prototype.sleep = function () {
  65504. if (this._physicsEngine) {
  65505. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  65506. }
  65507. return this;
  65508. };
  65509. /**
  65510. * Wake the body up.
  65511. */
  65512. PhysicsImpostor.prototype.wakeUp = function () {
  65513. if (this._physicsEngine) {
  65514. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  65515. }
  65516. return this;
  65517. };
  65518. PhysicsImpostor.prototype.clone = function (newObject) {
  65519. if (!newObject)
  65520. return null;
  65521. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  65522. };
  65523. PhysicsImpostor.prototype.dispose = function () {
  65524. var _this = this;
  65525. //no dispose if no physics engine is available.
  65526. if (!this._physicsEngine) {
  65527. return;
  65528. }
  65529. this._joints.forEach(function (j) {
  65530. if (_this._physicsEngine) {
  65531. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  65532. }
  65533. });
  65534. //dispose the physics body
  65535. this._physicsEngine.removeImpostor(this);
  65536. if (this.parent) {
  65537. this.parent.forceUpdate();
  65538. }
  65539. else {
  65540. /*this._object.getChildMeshes().forEach(function(mesh) {
  65541. if (mesh.physicsImpostor) {
  65542. if (disposeChildren) {
  65543. mesh.physicsImpostor.dispose();
  65544. mesh.physicsImpostor = null;
  65545. }
  65546. }
  65547. })*/
  65548. }
  65549. this._isDisposed = true;
  65550. };
  65551. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  65552. this._deltaPosition.copyFrom(position);
  65553. };
  65554. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  65555. if (!this._deltaRotation) {
  65556. this._deltaRotation = new BABYLON.Quaternion();
  65557. }
  65558. this._deltaRotation.copyFrom(rotation);
  65559. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  65560. };
  65561. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  65562. if (this._physicsEngine) {
  65563. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  65564. }
  65565. return this;
  65566. };
  65567. PhysicsImpostor.prototype.getRadius = function () {
  65568. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  65569. };
  65570. /**
  65571. * Sync a bone with this impostor
  65572. * @param bone The bone to sync to the impostor.
  65573. * @param boneMesh The mesh that the bone is influencing.
  65574. * @param jointPivot The pivot of the joint / bone in local space.
  65575. * @param distToJoint Optional distance from the impostor to the joint.
  65576. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65577. */
  65578. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  65579. var tempVec = PhysicsImpostor._tmpVecs[0];
  65580. var mesh = this.object;
  65581. if (mesh.rotationQuaternion) {
  65582. if (adjustRotation) {
  65583. var tempQuat = PhysicsImpostor._tmpQuat;
  65584. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  65585. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  65586. }
  65587. else {
  65588. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  65589. }
  65590. }
  65591. tempVec.x = 0;
  65592. tempVec.y = 0;
  65593. tempVec.z = 0;
  65594. if (jointPivot) {
  65595. tempVec.x = jointPivot.x;
  65596. tempVec.y = jointPivot.y;
  65597. tempVec.z = jointPivot.z;
  65598. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  65599. if (distToJoint === undefined || distToJoint === null) {
  65600. distToJoint = jointPivot.length();
  65601. }
  65602. tempVec.x *= distToJoint;
  65603. tempVec.y *= distToJoint;
  65604. tempVec.z *= distToJoint;
  65605. }
  65606. if (bone.getParent()) {
  65607. tempVec.addInPlace(mesh.getAbsolutePosition());
  65608. bone.setAbsolutePosition(tempVec, boneMesh);
  65609. }
  65610. else {
  65611. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  65612. boneMesh.position.x -= tempVec.x;
  65613. boneMesh.position.y -= tempVec.y;
  65614. boneMesh.position.z -= tempVec.z;
  65615. }
  65616. };
  65617. /**
  65618. * Sync impostor to a bone
  65619. * @param bone The bone that the impostor will be synced to.
  65620. * @param boneMesh The mesh that the bone is influencing.
  65621. * @param jointPivot The pivot of the joint / bone in local space.
  65622. * @param distToJoint Optional distance from the impostor to the joint.
  65623. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65624. * @param boneAxis Optional vector3 axis the bone is aligned with
  65625. */
  65626. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  65627. var mesh = this.object;
  65628. if (mesh.rotationQuaternion) {
  65629. if (adjustRotation) {
  65630. var tempQuat = PhysicsImpostor._tmpQuat;
  65631. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  65632. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  65633. }
  65634. else {
  65635. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  65636. }
  65637. }
  65638. var pos = PhysicsImpostor._tmpVecs[0];
  65639. var boneDir = PhysicsImpostor._tmpVecs[1];
  65640. if (!boneAxis) {
  65641. boneAxis = PhysicsImpostor._tmpVecs[2];
  65642. boneAxis.x = 0;
  65643. boneAxis.y = 1;
  65644. boneAxis.z = 0;
  65645. }
  65646. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  65647. bone.getAbsolutePositionToRef(boneMesh, pos);
  65648. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  65649. distToJoint = jointPivot.length();
  65650. }
  65651. if (distToJoint !== undefined && distToJoint !== null) {
  65652. pos.x += boneDir.x * distToJoint;
  65653. pos.y += boneDir.y * distToJoint;
  65654. pos.z += boneDir.z * distToJoint;
  65655. }
  65656. mesh.setAbsolutePosition(pos);
  65657. };
  65658. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  65659. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  65660. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65661. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  65662. //Impostor types
  65663. PhysicsImpostor.NoImpostor = 0;
  65664. PhysicsImpostor.SphereImpostor = 1;
  65665. PhysicsImpostor.BoxImpostor = 2;
  65666. PhysicsImpostor.PlaneImpostor = 3;
  65667. PhysicsImpostor.MeshImpostor = 4;
  65668. PhysicsImpostor.CylinderImpostor = 7;
  65669. PhysicsImpostor.ParticleImpostor = 8;
  65670. PhysicsImpostor.HeightmapImpostor = 9;
  65671. return PhysicsImpostor;
  65672. }());
  65673. BABYLON.PhysicsImpostor = PhysicsImpostor;
  65674. })(BABYLON || (BABYLON = {}));
  65675. //# sourceMappingURL=babylon.physicsImpostor.js.map
  65676. var BABYLON;
  65677. (function (BABYLON) {
  65678. var PhysicsEngine = /** @class */ (function () {
  65679. function PhysicsEngine(gravity, _physicsPlugin) {
  65680. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  65681. this._physicsPlugin = _physicsPlugin;
  65682. //new methods and parameters
  65683. this._impostors = [];
  65684. this._joints = [];
  65685. if (!this._physicsPlugin.isSupported()) {
  65686. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  65687. + "Please make sure it is included.");
  65688. }
  65689. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  65690. this.setGravity(gravity);
  65691. this.setTimeStep();
  65692. }
  65693. PhysicsEngine.prototype.setGravity = function (gravity) {
  65694. this.gravity = gravity;
  65695. this._physicsPlugin.setGravity(this.gravity);
  65696. };
  65697. /**
  65698. * Set the time step of the physics engine.
  65699. * default is 1/60.
  65700. * To slow it down, enter 1/600 for example.
  65701. * To speed it up, 1/30
  65702. * @param {number} newTimeStep the new timestep to apply to this world.
  65703. */
  65704. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  65705. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  65706. this._physicsPlugin.setTimeStep(newTimeStep);
  65707. };
  65708. /**
  65709. * Get the time step of the physics engine.
  65710. */
  65711. PhysicsEngine.prototype.getTimeStep = function () {
  65712. return this._physicsPlugin.getTimeStep();
  65713. };
  65714. PhysicsEngine.prototype.dispose = function () {
  65715. this._impostors.forEach(function (impostor) {
  65716. impostor.dispose();
  65717. });
  65718. this._physicsPlugin.dispose();
  65719. };
  65720. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  65721. return this._physicsPlugin.name;
  65722. };
  65723. /**
  65724. * Adding a new impostor for the impostor tracking.
  65725. * This will be done by the impostor itself.
  65726. * @param {PhysicsImpostor} impostor the impostor to add
  65727. */
  65728. PhysicsEngine.prototype.addImpostor = function (impostor) {
  65729. impostor.uniqueId = this._impostors.push(impostor);
  65730. //if no parent, generate the body
  65731. if (!impostor.parent) {
  65732. this._physicsPlugin.generatePhysicsBody(impostor);
  65733. }
  65734. };
  65735. /**
  65736. * Remove an impostor from the engine.
  65737. * This impostor and its mesh will not longer be updated by the physics engine.
  65738. * @param {PhysicsImpostor} impostor the impostor to remove
  65739. */
  65740. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  65741. var index = this._impostors.indexOf(impostor);
  65742. if (index > -1) {
  65743. var removed = this._impostors.splice(index, 1);
  65744. //Is it needed?
  65745. if (removed.length) {
  65746. //this will also remove it from the world.
  65747. removed[0].physicsBody = null;
  65748. }
  65749. }
  65750. };
  65751. /**
  65752. * Add a joint to the physics engine
  65753. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  65754. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  65755. * @param {PhysicsJoint} the joint that will connect both impostors.
  65756. */
  65757. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  65758. var impostorJoint = {
  65759. mainImpostor: mainImpostor,
  65760. connectedImpostor: connectedImpostor,
  65761. joint: joint
  65762. };
  65763. joint.physicsPlugin = this._physicsPlugin;
  65764. this._joints.push(impostorJoint);
  65765. this._physicsPlugin.generateJoint(impostorJoint);
  65766. };
  65767. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  65768. var matchingJoints = this._joints.filter(function (impostorJoint) {
  65769. return (impostorJoint.connectedImpostor === connectedImpostor
  65770. && impostorJoint.joint === joint
  65771. && impostorJoint.mainImpostor === mainImpostor);
  65772. });
  65773. if (matchingJoints.length) {
  65774. this._physicsPlugin.removeJoint(matchingJoints[0]);
  65775. //TODO remove it from the list as well
  65776. }
  65777. };
  65778. /**
  65779. * Called by the scene. no need to call it.
  65780. */
  65781. PhysicsEngine.prototype._step = function (delta) {
  65782. var _this = this;
  65783. //check if any mesh has no body / requires an update
  65784. this._impostors.forEach(function (impostor) {
  65785. if (impostor.isBodyInitRequired()) {
  65786. _this._physicsPlugin.generatePhysicsBody(impostor);
  65787. }
  65788. });
  65789. if (delta > 0.1) {
  65790. delta = 0.1;
  65791. }
  65792. else if (delta <= 0) {
  65793. delta = 1.0 / 60.0;
  65794. }
  65795. this._physicsPlugin.executeStep(delta, this._impostors);
  65796. };
  65797. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  65798. return this._physicsPlugin;
  65799. };
  65800. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  65801. for (var i = 0; i < this._impostors.length; ++i) {
  65802. if (this._impostors[i].object === object) {
  65803. return this._impostors[i];
  65804. }
  65805. }
  65806. return null;
  65807. };
  65808. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  65809. for (var i = 0; i < this._impostors.length; ++i) {
  65810. if (this._impostors[i].physicsBody === body) {
  65811. return this._impostors[i];
  65812. }
  65813. }
  65814. return null;
  65815. };
  65816. // Statics
  65817. PhysicsEngine.Epsilon = 0.001;
  65818. return PhysicsEngine;
  65819. }());
  65820. BABYLON.PhysicsEngine = PhysicsEngine;
  65821. })(BABYLON || (BABYLON = {}));
  65822. //# sourceMappingURL=babylon.physicsEngine.js.map
  65823. var BABYLON;
  65824. (function (BABYLON) {
  65825. var CannonJSPlugin = /** @class */ (function () {
  65826. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  65827. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  65828. if (iterations === void 0) { iterations = 10; }
  65829. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  65830. this.name = "CannonJSPlugin";
  65831. this._physicsMaterials = new Array();
  65832. this._fixedTimeStep = 1 / 60;
  65833. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  65834. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  65835. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  65836. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  65837. this._tmpPosition = BABYLON.Vector3.Zero();
  65838. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  65839. this._tmpUnityRotation = new BABYLON.Quaternion();
  65840. if (!this.isSupported()) {
  65841. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  65842. return;
  65843. }
  65844. this.world = new this.BJSCANNON.World();
  65845. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  65846. this.world.solver.iterations = iterations;
  65847. }
  65848. CannonJSPlugin.prototype.setGravity = function (gravity) {
  65849. this.world.gravity.copy(gravity);
  65850. };
  65851. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  65852. this._fixedTimeStep = timeStep;
  65853. };
  65854. CannonJSPlugin.prototype.getTimeStep = function () {
  65855. return this._fixedTimeStep;
  65856. };
  65857. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  65858. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  65859. };
  65860. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  65861. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65862. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65863. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  65864. };
  65865. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  65866. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65867. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65868. impostor.physicsBody.applyForce(impulse, worldPoint);
  65869. };
  65870. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  65871. //parent-child relationship. Does this impostor has a parent impostor?
  65872. if (impostor.parent) {
  65873. if (impostor.physicsBody) {
  65874. this.removePhysicsBody(impostor);
  65875. //TODO is that needed?
  65876. impostor.forceUpdate();
  65877. }
  65878. return;
  65879. }
  65880. //should a new body be created for this impostor?
  65881. if (impostor.isBodyInitRequired()) {
  65882. var shape = this._createShape(impostor);
  65883. //unregister events, if body is being changed
  65884. var oldBody = impostor.physicsBody;
  65885. if (oldBody) {
  65886. this.removePhysicsBody(impostor);
  65887. }
  65888. //create the body and material
  65889. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  65890. var bodyCreationObject = {
  65891. mass: impostor.getParam("mass"),
  65892. material: material
  65893. };
  65894. // A simple extend, in case native options were used.
  65895. var nativeOptions = impostor.getParam("nativeOptions");
  65896. for (var key in nativeOptions) {
  65897. if (nativeOptions.hasOwnProperty(key)) {
  65898. bodyCreationObject[key] = nativeOptions[key];
  65899. }
  65900. }
  65901. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  65902. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  65903. this.world.addEventListener("preStep", impostor.beforeStep);
  65904. this.world.addEventListener("postStep", impostor.afterStep);
  65905. impostor.physicsBody.addShape(shape);
  65906. this.world.add(impostor.physicsBody);
  65907. //try to keep the body moving in the right direction by taking old properties.
  65908. //Should be tested!
  65909. if (oldBody) {
  65910. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  65911. impostor.physicsBody[param].copy(oldBody[param]);
  65912. });
  65913. }
  65914. this._processChildMeshes(impostor);
  65915. }
  65916. //now update the body's transformation
  65917. this._updatePhysicsBodyTransformation(impostor);
  65918. };
  65919. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  65920. var _this = this;
  65921. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  65922. var currentRotation = mainImpostor.object.rotationQuaternion;
  65923. if (meshChildren.length) {
  65924. var processMesh = function (localPosition, mesh) {
  65925. if (!currentRotation || !mesh.rotationQuaternion) {
  65926. return;
  65927. }
  65928. var childImpostor = mesh.getPhysicsImpostor();
  65929. if (childImpostor) {
  65930. var parent = childImpostor.parent;
  65931. if (parent !== mainImpostor) {
  65932. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  65933. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  65934. if (childImpostor.physicsBody) {
  65935. _this.removePhysicsBody(childImpostor);
  65936. childImpostor.physicsBody = null;
  65937. }
  65938. childImpostor.parent = mainImpostor;
  65939. childImpostor.resetUpdateFlags();
  65940. 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));
  65941. //Add the mass of the children.
  65942. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  65943. }
  65944. }
  65945. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  65946. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  65947. };
  65948. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  65949. }
  65950. };
  65951. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  65952. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  65953. this.world.removeEventListener("preStep", impostor.beforeStep);
  65954. this.world.removeEventListener("postStep", impostor.afterStep);
  65955. this.world.remove(impostor.physicsBody);
  65956. };
  65957. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  65958. var mainBody = impostorJoint.mainImpostor.physicsBody;
  65959. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  65960. if (!mainBody || !connectedBody) {
  65961. return;
  65962. }
  65963. var constraint;
  65964. var jointData = impostorJoint.joint.jointData;
  65965. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  65966. var constraintData = {
  65967. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  65968. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  65969. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  65970. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  65971. maxForce: jointData.nativeParams.maxForce,
  65972. collideConnected: !!jointData.collision
  65973. };
  65974. switch (impostorJoint.joint.type) {
  65975. case BABYLON.PhysicsJoint.HingeJoint:
  65976. case BABYLON.PhysicsJoint.Hinge2Joint:
  65977. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  65978. break;
  65979. case BABYLON.PhysicsJoint.DistanceJoint:
  65980. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  65981. break;
  65982. case BABYLON.PhysicsJoint.SpringJoint:
  65983. var springData = jointData;
  65984. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  65985. restLength: springData.length,
  65986. stiffness: springData.stiffness,
  65987. damping: springData.damping,
  65988. localAnchorA: constraintData.pivotA,
  65989. localAnchorB: constraintData.pivotB
  65990. });
  65991. break;
  65992. case BABYLON.PhysicsJoint.LockJoint:
  65993. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  65994. break;
  65995. case BABYLON.PhysicsJoint.PointToPointJoint:
  65996. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  65997. default:
  65998. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  65999. break;
  66000. }
  66001. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  66002. constraint.collideConnected = !!jointData.collision;
  66003. impostorJoint.joint.physicsJoint = constraint;
  66004. //don't add spring as constraint, as it is not one.
  66005. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  66006. this.world.addConstraint(constraint);
  66007. }
  66008. else {
  66009. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  66010. constraint.applyForce();
  66011. });
  66012. }
  66013. };
  66014. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66015. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  66016. };
  66017. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  66018. var index;
  66019. var mat;
  66020. for (index = 0; index < this._physicsMaterials.length; index++) {
  66021. mat = this._physicsMaterials[index];
  66022. if (mat.friction === friction && mat.restitution === restitution) {
  66023. return mat;
  66024. }
  66025. }
  66026. var currentMat = new this.BJSCANNON.Material(name);
  66027. currentMat.friction = friction;
  66028. currentMat.restitution = restitution;
  66029. this._physicsMaterials.push(currentMat);
  66030. return currentMat;
  66031. };
  66032. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  66033. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  66034. };
  66035. CannonJSPlugin.prototype._createShape = function (impostor) {
  66036. var object = impostor.object;
  66037. var returnValue;
  66038. var extendSize = impostor.getObjectExtendSize();
  66039. switch (impostor.type) {
  66040. case BABYLON.PhysicsImpostor.SphereImpostor:
  66041. var radiusX = extendSize.x;
  66042. var radiusY = extendSize.y;
  66043. var radiusZ = extendSize.z;
  66044. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  66045. break;
  66046. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  66047. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66048. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  66049. break;
  66050. case BABYLON.PhysicsImpostor.BoxImpostor:
  66051. var box = extendSize.scale(0.5);
  66052. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  66053. break;
  66054. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66055. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  66056. returnValue = new this.BJSCANNON.Plane();
  66057. break;
  66058. case BABYLON.PhysicsImpostor.MeshImpostor:
  66059. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  66060. var rawFaces = object.getIndices ? object.getIndices() : [];
  66061. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  66062. returnValue = new this.BJSCANNON.Trimesh(rawVerts, rawFaces);
  66063. break;
  66064. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  66065. returnValue = this._createHeightmap(object);
  66066. break;
  66067. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66068. returnValue = new this.BJSCANNON.Particle();
  66069. break;
  66070. }
  66071. return returnValue;
  66072. };
  66073. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  66074. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  66075. var matrix = new Array();
  66076. //For now pointDepth will not be used and will be automatically calculated.
  66077. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  66078. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  66079. var boundingInfo = (object.getBoundingInfo());
  66080. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.z);
  66081. var minY = boundingInfo.boundingBox.extendSizeWorld.y;
  66082. var elementSize = dim * 2 / arraySize;
  66083. for (var i = 0; i < pos.length; i = i + 3) {
  66084. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  66085. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  66086. var y = pos[i + 1] + minY;
  66087. if (!matrix[x]) {
  66088. matrix[x] = [];
  66089. }
  66090. if (!matrix[x][z]) {
  66091. matrix[x][z] = y;
  66092. }
  66093. matrix[x][z] = Math.max(y, matrix[x][z]);
  66094. }
  66095. for (var x = 0; x <= arraySize; ++x) {
  66096. if (!matrix[x]) {
  66097. var loc = 1;
  66098. while (!matrix[(x + loc) % arraySize]) {
  66099. loc++;
  66100. }
  66101. matrix[x] = matrix[(x + loc) % arraySize].slice();
  66102. //console.log("missing x", x);
  66103. }
  66104. for (var z = 0; z <= arraySize; ++z) {
  66105. if (!matrix[x][z]) {
  66106. var loc = 1;
  66107. var newValue;
  66108. while (newValue === undefined) {
  66109. newValue = matrix[x][(z + loc++) % arraySize];
  66110. }
  66111. matrix[x][z] = newValue;
  66112. }
  66113. }
  66114. }
  66115. var shape = new this.BJSCANNON.Heightfield(matrix, {
  66116. elementSize: elementSize
  66117. });
  66118. //For future reference, needed for body transformation
  66119. shape.minY = minY;
  66120. return shape;
  66121. };
  66122. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  66123. var object = impostor.object;
  66124. //make sure it is updated...
  66125. object.computeWorldMatrix && object.computeWorldMatrix(true);
  66126. // The delta between the mesh position and the mesh bounding box center
  66127. var center = impostor.getObjectCenter();
  66128. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  66129. this._tmpPosition.copyFrom(center);
  66130. var quaternion = object.rotationQuaternion;
  66131. if (!quaternion) {
  66132. return;
  66133. }
  66134. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  66135. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  66136. //-90 DEG in X, precalculated
  66137. quaternion = quaternion.multiply(this._minus90X);
  66138. //Invert! (Precalculated, 90 deg in X)
  66139. //No need to clone. this will never change.
  66140. impostor.setDeltaRotation(this._plus90X);
  66141. }
  66142. //If it is a heightfield, if should be centered.
  66143. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  66144. var mesh = object;
  66145. var boundingInfo = mesh.getBoundingInfo();
  66146. //calculate the correct body position:
  66147. var rotationQuaternion = mesh.rotationQuaternion;
  66148. mesh.rotationQuaternion = this._tmpUnityRotation;
  66149. mesh.computeWorldMatrix(true);
  66150. //get original center with no rotation
  66151. var c = center.clone();
  66152. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  66153. //rotation is back
  66154. mesh.rotationQuaternion = rotationQuaternion;
  66155. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  66156. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  66157. mesh.setPivotMatrix(p);
  66158. mesh.computeWorldMatrix(true);
  66159. //calculate the translation
  66160. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  66161. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  66162. //add it inverted to the delta
  66163. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  66164. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  66165. mesh.setPivotMatrix(oldPivot);
  66166. mesh.computeWorldMatrix(true);
  66167. }
  66168. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  66169. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  66170. this._tmpPosition.copyFrom(object.position);
  66171. }
  66172. impostor.setDeltaPosition(this._tmpDeltaPosition);
  66173. //Now update the impostor object
  66174. impostor.physicsBody.position.copy(this._tmpPosition);
  66175. impostor.physicsBody.quaternion.copy(quaternion);
  66176. };
  66177. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66178. impostor.object.position.copyFrom(impostor.physicsBody.position);
  66179. if (impostor.object.rotationQuaternion) {
  66180. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  66181. }
  66182. };
  66183. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66184. impostor.physicsBody.position.copy(newPosition);
  66185. impostor.physicsBody.quaternion.copy(newRotation);
  66186. };
  66187. CannonJSPlugin.prototype.isSupported = function () {
  66188. return this.BJSCANNON !== undefined;
  66189. };
  66190. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66191. impostor.physicsBody.velocity.copy(velocity);
  66192. };
  66193. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66194. impostor.physicsBody.angularVelocity.copy(velocity);
  66195. };
  66196. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66197. var v = impostor.physicsBody.velocity;
  66198. if (!v) {
  66199. return null;
  66200. }
  66201. return new BABYLON.Vector3(v.x, v.y, v.z);
  66202. };
  66203. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66204. var v = impostor.physicsBody.angularVelocity;
  66205. if (!v) {
  66206. return null;
  66207. }
  66208. return new BABYLON.Vector3(v.x, v.y, v.z);
  66209. };
  66210. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66211. impostor.physicsBody.mass = mass;
  66212. impostor.physicsBody.updateMassProperties();
  66213. };
  66214. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  66215. return impostor.physicsBody.mass;
  66216. };
  66217. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  66218. return impostor.physicsBody.material.friction;
  66219. };
  66220. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66221. impostor.physicsBody.material.friction = friction;
  66222. };
  66223. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66224. return impostor.physicsBody.material.restitution;
  66225. };
  66226. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66227. impostor.physicsBody.material.restitution = restitution;
  66228. };
  66229. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  66230. impostor.physicsBody.sleep();
  66231. };
  66232. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  66233. impostor.physicsBody.wakeUp();
  66234. };
  66235. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66236. joint.physicsJoint.distance = maxDistance;
  66237. };
  66238. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66239. // if (!motorIndex) {
  66240. // joint.physicsJoint.enableMotor();
  66241. // }
  66242. // }
  66243. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66244. // if (!motorIndex) {
  66245. // joint.physicsJoint.disableMotor();
  66246. // }
  66247. // }
  66248. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66249. if (!motorIndex) {
  66250. joint.physicsJoint.enableMotor();
  66251. joint.physicsJoint.setMotorSpeed(speed);
  66252. if (maxForce) {
  66253. this.setLimit(joint, maxForce);
  66254. }
  66255. }
  66256. };
  66257. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  66258. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  66259. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  66260. };
  66261. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66262. var body = impostor.physicsBody;
  66263. mesh.position.x = body.position.x;
  66264. mesh.position.y = body.position.y;
  66265. mesh.position.z = body.position.z;
  66266. if (mesh.rotationQuaternion) {
  66267. mesh.rotationQuaternion.x = body.quaternion.x;
  66268. mesh.rotationQuaternion.y = body.quaternion.y;
  66269. mesh.rotationQuaternion.z = body.quaternion.z;
  66270. mesh.rotationQuaternion.w = body.quaternion.w;
  66271. }
  66272. };
  66273. CannonJSPlugin.prototype.getRadius = function (impostor) {
  66274. var shape = impostor.physicsBody.shapes[0];
  66275. return shape.boundingSphereRadius;
  66276. };
  66277. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66278. var shape = impostor.physicsBody.shapes[0];
  66279. result.x = shape.halfExtents.x * 2;
  66280. result.y = shape.halfExtents.y * 2;
  66281. result.z = shape.halfExtents.z * 2;
  66282. };
  66283. CannonJSPlugin.prototype.dispose = function () {
  66284. };
  66285. return CannonJSPlugin;
  66286. }());
  66287. BABYLON.CannonJSPlugin = CannonJSPlugin;
  66288. })(BABYLON || (BABYLON = {}));
  66289. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  66290. var BABYLON;
  66291. (function (BABYLON) {
  66292. var OimoJSPlugin = /** @class */ (function () {
  66293. function OimoJSPlugin(iterations) {
  66294. this.name = "OimoJSPlugin";
  66295. this._tmpImpostorsArray = [];
  66296. this._tmpPositionVector = BABYLON.Vector3.Zero();
  66297. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  66298. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  66299. this.world.worldscale(1);
  66300. this.world.clear();
  66301. //making sure no stats are calculated
  66302. this.world.isNoStat = true;
  66303. }
  66304. OimoJSPlugin.prototype.setGravity = function (gravity) {
  66305. this.world.gravity.copy(gravity);
  66306. };
  66307. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  66308. this.world.timeStep = timeStep;
  66309. };
  66310. OimoJSPlugin.prototype.getTimeStep = function () {
  66311. return this.world.timeStep;
  66312. };
  66313. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  66314. var _this = this;
  66315. impostors.forEach(function (impostor) {
  66316. impostor.beforeStep();
  66317. });
  66318. this.world.step();
  66319. impostors.forEach(function (impostor) {
  66320. impostor.afterStep();
  66321. //update the ordered impostors array
  66322. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  66323. });
  66324. //check for collisions
  66325. var contact = this.world.contacts;
  66326. while (contact !== null) {
  66327. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  66328. contact = contact.next;
  66329. continue;
  66330. }
  66331. //is this body colliding with any other? get the impostor
  66332. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  66333. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  66334. if (!mainImpostor || !collidingImpostor) {
  66335. contact = contact.next;
  66336. continue;
  66337. }
  66338. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  66339. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  66340. contact = contact.next;
  66341. }
  66342. };
  66343. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66344. var mass = impostor.physicsBody.massInfo.mass;
  66345. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  66346. };
  66347. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66348. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  66349. this.applyImpulse(impostor, force, contactPoint);
  66350. };
  66351. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66352. var _this = this;
  66353. //parent-child relationship. Does this impostor has a parent impostor?
  66354. if (impostor.parent) {
  66355. if (impostor.physicsBody) {
  66356. this.removePhysicsBody(impostor);
  66357. //TODO is that needed?
  66358. impostor.forceUpdate();
  66359. }
  66360. return;
  66361. }
  66362. if (impostor.isBodyInitRequired()) {
  66363. var bodyConfig = {
  66364. name: impostor.uniqueId,
  66365. //Oimo must have mass, also for static objects.
  66366. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  66367. size: [],
  66368. type: [],
  66369. pos: [],
  66370. rot: [],
  66371. move: impostor.getParam("mass") !== 0,
  66372. //Supporting older versions of Oimo
  66373. world: this.world
  66374. };
  66375. var impostors = [impostor];
  66376. var addToArray = function (parent) {
  66377. if (!parent.getChildMeshes)
  66378. return;
  66379. parent.getChildMeshes().forEach(function (m) {
  66380. if (m.physicsImpostor) {
  66381. impostors.push(m.physicsImpostor);
  66382. //m.physicsImpostor._init();
  66383. }
  66384. });
  66385. };
  66386. addToArray(impostor.object);
  66387. var checkWithEpsilon_1 = function (value) {
  66388. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  66389. };
  66390. impostors.forEach(function (i) {
  66391. if (!impostor.object.rotationQuaternion) {
  66392. return;
  66393. }
  66394. //get the correct bounding box
  66395. var oldQuaternion = i.object.rotationQuaternion;
  66396. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  66397. x: impostor.object.rotationQuaternion.x,
  66398. y: impostor.object.rotationQuaternion.y,
  66399. z: impostor.object.rotationQuaternion.z,
  66400. s: impostor.object.rotationQuaternion.w
  66401. });
  66402. var extendSize = i.getObjectExtendSize();
  66403. if (i === impostor) {
  66404. var center = impostor.getObjectCenter();
  66405. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  66406. //Can also use Array.prototype.push.apply
  66407. bodyConfig.pos.push(center.x);
  66408. bodyConfig.pos.push(center.y);
  66409. bodyConfig.pos.push(center.z);
  66410. //tmp solution
  66411. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66412. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66413. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66414. }
  66415. else {
  66416. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  66417. bodyConfig.pos.push(localPosition.x);
  66418. bodyConfig.pos.push(localPosition.y);
  66419. bodyConfig.pos.push(localPosition.z);
  66420. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  66421. bodyConfig.rot.push(0);
  66422. bodyConfig.rot.push(0);
  66423. bodyConfig.rot.push(0);
  66424. }
  66425. // register mesh
  66426. switch (i.type) {
  66427. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66428. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  66429. case BABYLON.PhysicsImpostor.SphereImpostor:
  66430. var radiusX = extendSize.x;
  66431. var radiusY = extendSize.y;
  66432. var radiusZ = extendSize.z;
  66433. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  66434. bodyConfig.type.push('sphere');
  66435. //due to the way oimo works with compounds, add 3 times
  66436. bodyConfig.size.push(size);
  66437. bodyConfig.size.push(size);
  66438. bodyConfig.size.push(size);
  66439. break;
  66440. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66441. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  66442. var sizeY = checkWithEpsilon_1(extendSize.y);
  66443. bodyConfig.type.push('cylinder');
  66444. bodyConfig.size.push(sizeX);
  66445. bodyConfig.size.push(sizeY);
  66446. //due to the way oimo works with compounds, add one more value.
  66447. bodyConfig.size.push(sizeY);
  66448. break;
  66449. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66450. case BABYLON.PhysicsImpostor.BoxImpostor:
  66451. default:
  66452. var sizeX = checkWithEpsilon_1(extendSize.x);
  66453. var sizeY = checkWithEpsilon_1(extendSize.y);
  66454. var sizeZ = checkWithEpsilon_1(extendSize.z);
  66455. bodyConfig.type.push('box');
  66456. bodyConfig.size.push(sizeX);
  66457. bodyConfig.size.push(sizeY);
  66458. bodyConfig.size.push(sizeZ);
  66459. break;
  66460. }
  66461. //actually not needed, but hey...
  66462. i.object.rotationQuaternion = oldQuaternion;
  66463. });
  66464. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  66465. }
  66466. else {
  66467. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  66468. }
  66469. impostor.setDeltaPosition(this._tmpPositionVector);
  66470. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  66471. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  66472. };
  66473. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66474. //impostor.physicsBody.dispose();
  66475. //Same as : (older oimo versions)
  66476. this.world.removeRigidBody(impostor.physicsBody);
  66477. };
  66478. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66479. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66480. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66481. if (!mainBody || !connectedBody) {
  66482. return;
  66483. }
  66484. var jointData = impostorJoint.joint.jointData;
  66485. var options = jointData.nativeParams || {};
  66486. var type;
  66487. var nativeJointData = {
  66488. body1: mainBody,
  66489. body2: connectedBody,
  66490. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  66491. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  66492. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  66493. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  66494. min: options.min,
  66495. max: options.max,
  66496. collision: options.collision || jointData.collision,
  66497. spring: options.spring,
  66498. //supporting older version of Oimo
  66499. world: this.world
  66500. };
  66501. switch (impostorJoint.joint.type) {
  66502. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66503. type = "jointBall";
  66504. break;
  66505. case BABYLON.PhysicsJoint.SpringJoint:
  66506. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  66507. var springData = jointData;
  66508. nativeJointData.min = springData.length || nativeJointData.min;
  66509. //Max should also be set, just make sure it is at least min
  66510. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  66511. case BABYLON.PhysicsJoint.DistanceJoint:
  66512. type = "jointDistance";
  66513. nativeJointData.max = jointData.maxDistance;
  66514. break;
  66515. case BABYLON.PhysicsJoint.PrismaticJoint:
  66516. type = "jointPrisme";
  66517. break;
  66518. case BABYLON.PhysicsJoint.SliderJoint:
  66519. type = "jointSlide";
  66520. break;
  66521. case BABYLON.PhysicsJoint.WheelJoint:
  66522. type = "jointWheel";
  66523. break;
  66524. case BABYLON.PhysicsJoint.HingeJoint:
  66525. default:
  66526. type = "jointHinge";
  66527. break;
  66528. }
  66529. nativeJointData.type = type;
  66530. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  66531. };
  66532. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66533. //Bug in Oimo prevents us from disposing a joint in the playground
  66534. //joint.joint.physicsJoint.dispose();
  66535. //So we will bruteforce it!
  66536. try {
  66537. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  66538. }
  66539. catch (e) {
  66540. BABYLON.Tools.Warn(e);
  66541. }
  66542. };
  66543. OimoJSPlugin.prototype.isSupported = function () {
  66544. return this.BJSOIMO !== undefined;
  66545. };
  66546. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66547. if (!impostor.physicsBody.sleeping) {
  66548. //TODO check that
  66549. if (impostor.physicsBody.shapes.next) {
  66550. var parentShape = this._getLastShape(impostor.physicsBody);
  66551. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  66552. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  66553. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  66554. }
  66555. else {
  66556. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  66557. }
  66558. if (impostor.object.rotationQuaternion) {
  66559. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  66560. impostor.object.rotationQuaternion.normalize();
  66561. }
  66562. }
  66563. };
  66564. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66565. var body = impostor.physicsBody;
  66566. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  66567. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  66568. body.syncShapes();
  66569. body.awake();
  66570. };
  66571. OimoJSPlugin.prototype._getLastShape = function (body) {
  66572. var lastShape = body.shapes;
  66573. while (lastShape.next) {
  66574. lastShape = lastShape.next;
  66575. }
  66576. return lastShape;
  66577. };
  66578. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66579. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  66580. };
  66581. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66582. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  66583. };
  66584. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66585. var v = impostor.physicsBody.linearVelocity;
  66586. if (!v) {
  66587. return null;
  66588. }
  66589. return new BABYLON.Vector3(v.x, v.y, v.z);
  66590. };
  66591. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66592. var v = impostor.physicsBody.angularVelocity;
  66593. if (!v) {
  66594. return null;
  66595. }
  66596. return new BABYLON.Vector3(v.x, v.y, v.z);
  66597. };
  66598. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66599. var staticBody = mass === 0;
  66600. //this will actually set the body's density and not its mass.
  66601. //But this is how oimo treats the mass variable.
  66602. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  66603. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  66604. };
  66605. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  66606. return impostor.physicsBody.shapes.density;
  66607. };
  66608. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  66609. return impostor.physicsBody.shapes.friction;
  66610. };
  66611. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66612. impostor.physicsBody.shapes.friction = friction;
  66613. };
  66614. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66615. return impostor.physicsBody.shapes.restitution;
  66616. };
  66617. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66618. impostor.physicsBody.shapes.restitution = restitution;
  66619. };
  66620. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  66621. impostor.physicsBody.sleep();
  66622. };
  66623. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  66624. impostor.physicsBody.awake();
  66625. };
  66626. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66627. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  66628. if (minDistance !== void 0) {
  66629. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  66630. }
  66631. };
  66632. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66633. //TODO separate rotational and transational motors.
  66634. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66635. if (motor) {
  66636. motor.setMotor(speed, maxForce);
  66637. }
  66638. };
  66639. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  66640. //TODO separate rotational and transational motors.
  66641. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66642. if (motor) {
  66643. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  66644. }
  66645. };
  66646. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66647. var body = impostor.physicsBody;
  66648. mesh.position.x = body.position.x;
  66649. mesh.position.y = body.position.y;
  66650. mesh.position.z = body.position.z;
  66651. if (mesh.rotationQuaternion) {
  66652. mesh.rotationQuaternion.x = body.orientation.x;
  66653. mesh.rotationQuaternion.y = body.orientation.y;
  66654. mesh.rotationQuaternion.z = body.orientation.z;
  66655. mesh.rotationQuaternion.w = body.orientation.s;
  66656. }
  66657. };
  66658. OimoJSPlugin.prototype.getRadius = function (impostor) {
  66659. return impostor.physicsBody.shapes.radius;
  66660. };
  66661. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66662. var shape = impostor.physicsBody.shapes;
  66663. result.x = shape.halfWidth * 2;
  66664. result.y = shape.halfHeight * 2;
  66665. result.z = shape.halfDepth * 2;
  66666. };
  66667. OimoJSPlugin.prototype.dispose = function () {
  66668. this.world.clear();
  66669. };
  66670. return OimoJSPlugin;
  66671. }());
  66672. BABYLON.OimoJSPlugin = OimoJSPlugin;
  66673. })(BABYLON || (BABYLON = {}));
  66674. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  66675. var BABYLON;
  66676. (function (BABYLON) {
  66677. var Internals;
  66678. (function (Internals) {
  66679. /*
  66680. * Based on jsTGALoader - Javascript loader for TGA file
  66681. * By Vincent Thibault
  66682. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  66683. */
  66684. var TGATools = /** @class */ (function () {
  66685. function TGATools() {
  66686. }
  66687. TGATools.GetTGAHeader = function (data) {
  66688. var offset = 0;
  66689. var header = {
  66690. id_length: data[offset++],
  66691. colormap_type: data[offset++],
  66692. image_type: data[offset++],
  66693. colormap_index: data[offset++] | data[offset++] << 8,
  66694. colormap_length: data[offset++] | data[offset++] << 8,
  66695. colormap_size: data[offset++],
  66696. origin: [
  66697. data[offset++] | data[offset++] << 8,
  66698. data[offset++] | data[offset++] << 8
  66699. ],
  66700. width: data[offset++] | data[offset++] << 8,
  66701. height: data[offset++] | data[offset++] << 8,
  66702. pixel_size: data[offset++],
  66703. flags: data[offset++]
  66704. };
  66705. return header;
  66706. };
  66707. TGATools.UploadContent = function (gl, data) {
  66708. // Not enough data to contain header ?
  66709. if (data.length < 19) {
  66710. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  66711. return;
  66712. }
  66713. // Read Header
  66714. var offset = 18;
  66715. var header = TGATools.GetTGAHeader(data);
  66716. // Assume it's a valid Targa file.
  66717. if (header.id_length + offset > data.length) {
  66718. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  66719. return;
  66720. }
  66721. // Skip not needed data
  66722. offset += header.id_length;
  66723. var use_rle = false;
  66724. var use_pal = false;
  66725. var use_rgb = false;
  66726. var use_grey = false;
  66727. // Get some informations.
  66728. switch (header.image_type) {
  66729. case TGATools._TYPE_RLE_INDEXED:
  66730. use_rle = true;
  66731. case TGATools._TYPE_INDEXED:
  66732. use_pal = true;
  66733. break;
  66734. case TGATools._TYPE_RLE_RGB:
  66735. use_rle = true;
  66736. case TGATools._TYPE_RGB:
  66737. use_rgb = true;
  66738. break;
  66739. case TGATools._TYPE_RLE_GREY:
  66740. use_rle = true;
  66741. case TGATools._TYPE_GREY:
  66742. use_grey = true;
  66743. break;
  66744. }
  66745. var pixel_data;
  66746. // var numAlphaBits = header.flags & 0xf;
  66747. var pixel_size = header.pixel_size >> 3;
  66748. var pixel_total = header.width * header.height * pixel_size;
  66749. // Read palettes
  66750. var palettes;
  66751. if (use_pal) {
  66752. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  66753. }
  66754. // Read LRE
  66755. if (use_rle) {
  66756. pixel_data = new Uint8Array(pixel_total);
  66757. var c, count, i;
  66758. var localOffset = 0;
  66759. var pixels = new Uint8Array(pixel_size);
  66760. while (offset < pixel_total && localOffset < pixel_total) {
  66761. c = data[offset++];
  66762. count = (c & 0x7f) + 1;
  66763. // RLE pixels
  66764. if (c & 0x80) {
  66765. // Bind pixel tmp array
  66766. for (i = 0; i < pixel_size; ++i) {
  66767. pixels[i] = data[offset++];
  66768. }
  66769. // Copy pixel array
  66770. for (i = 0; i < count; ++i) {
  66771. pixel_data.set(pixels, localOffset + i * pixel_size);
  66772. }
  66773. localOffset += pixel_size * count;
  66774. }
  66775. else {
  66776. count *= pixel_size;
  66777. for (i = 0; i < count; ++i) {
  66778. pixel_data[localOffset + i] = data[offset++];
  66779. }
  66780. localOffset += count;
  66781. }
  66782. }
  66783. }
  66784. else {
  66785. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  66786. }
  66787. // Load to texture
  66788. var x_start, y_start, x_step, y_step, y_end, x_end;
  66789. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  66790. default:
  66791. case TGATools._ORIGIN_UL:
  66792. x_start = 0;
  66793. x_step = 1;
  66794. x_end = header.width;
  66795. y_start = 0;
  66796. y_step = 1;
  66797. y_end = header.height;
  66798. break;
  66799. case TGATools._ORIGIN_BL:
  66800. x_start = 0;
  66801. x_step = 1;
  66802. x_end = header.width;
  66803. y_start = header.height - 1;
  66804. y_step = -1;
  66805. y_end = -1;
  66806. break;
  66807. case TGATools._ORIGIN_UR:
  66808. x_start = header.width - 1;
  66809. x_step = -1;
  66810. x_end = -1;
  66811. y_start = 0;
  66812. y_step = 1;
  66813. y_end = header.height;
  66814. break;
  66815. case TGATools._ORIGIN_BR:
  66816. x_start = header.width - 1;
  66817. x_step = -1;
  66818. x_end = -1;
  66819. y_start = header.height - 1;
  66820. y_step = -1;
  66821. y_end = -1;
  66822. break;
  66823. }
  66824. // Load the specify method
  66825. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  66826. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  66827. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  66828. };
  66829. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66830. var image = pixel_data, colormap = palettes;
  66831. var width = header.width, height = header.height;
  66832. var color, i = 0, x, y;
  66833. var imageData = new Uint8Array(width * height * 4);
  66834. for (y = y_start; y !== y_end; y += y_step) {
  66835. for (x = x_start; x !== x_end; x += x_step, i++) {
  66836. color = image[i];
  66837. imageData[(x + width * y) * 4 + 3] = 255;
  66838. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  66839. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  66840. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  66841. }
  66842. }
  66843. return imageData;
  66844. };
  66845. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66846. var image = pixel_data;
  66847. var width = header.width, height = header.height;
  66848. var color, i = 0, x, y;
  66849. var imageData = new Uint8Array(width * height * 4);
  66850. for (y = y_start; y !== y_end; y += y_step) {
  66851. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66852. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  66853. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  66854. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  66855. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  66856. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  66857. }
  66858. }
  66859. return imageData;
  66860. };
  66861. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66862. var image = pixel_data;
  66863. var width = header.width, height = header.height;
  66864. var i = 0, x, y;
  66865. var imageData = new Uint8Array(width * height * 4);
  66866. for (y = y_start; y !== y_end; y += y_step) {
  66867. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  66868. imageData[(x + width * y) * 4 + 3] = 255;
  66869. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66870. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66871. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66872. }
  66873. }
  66874. return imageData;
  66875. };
  66876. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66877. var image = pixel_data;
  66878. var width = header.width, height = header.height;
  66879. var i = 0, x, y;
  66880. var imageData = new Uint8Array(width * height * 4);
  66881. for (y = y_start; y !== y_end; y += y_step) {
  66882. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  66883. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66884. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66885. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66886. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  66887. }
  66888. }
  66889. return imageData;
  66890. };
  66891. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66892. var image = pixel_data;
  66893. var width = header.width, height = header.height;
  66894. var color, i = 0, x, y;
  66895. var imageData = new Uint8Array(width * height * 4);
  66896. for (y = y_start; y !== y_end; y += y_step) {
  66897. for (x = x_start; x !== x_end; x += x_step, i++) {
  66898. color = image[i];
  66899. imageData[(x + width * y) * 4 + 0] = color;
  66900. imageData[(x + width * y) * 4 + 1] = color;
  66901. imageData[(x + width * y) * 4 + 2] = color;
  66902. imageData[(x + width * y) * 4 + 3] = 255;
  66903. }
  66904. }
  66905. return imageData;
  66906. };
  66907. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66908. var image = pixel_data;
  66909. var width = header.width, height = header.height;
  66910. var i = 0, x, y;
  66911. var imageData = new Uint8Array(width * height * 4);
  66912. for (y = y_start; y !== y_end; y += y_step) {
  66913. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66914. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  66915. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  66916. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66917. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  66918. }
  66919. }
  66920. return imageData;
  66921. };
  66922. //private static _TYPE_NO_DATA = 0;
  66923. TGATools._TYPE_INDEXED = 1;
  66924. TGATools._TYPE_RGB = 2;
  66925. TGATools._TYPE_GREY = 3;
  66926. TGATools._TYPE_RLE_INDEXED = 9;
  66927. TGATools._TYPE_RLE_RGB = 10;
  66928. TGATools._TYPE_RLE_GREY = 11;
  66929. TGATools._ORIGIN_MASK = 0x30;
  66930. TGATools._ORIGIN_SHIFT = 0x04;
  66931. TGATools._ORIGIN_BL = 0x00;
  66932. TGATools._ORIGIN_BR = 0x01;
  66933. TGATools._ORIGIN_UL = 0x02;
  66934. TGATools._ORIGIN_UR = 0x03;
  66935. return TGATools;
  66936. }());
  66937. Internals.TGATools = TGATools;
  66938. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  66939. })(BABYLON || (BABYLON = {}));
  66940. //# sourceMappingURL=babylon.tga.js.map
  66941. var BABYLON;
  66942. (function (BABYLON) {
  66943. var Internals;
  66944. (function (Internals) {
  66945. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  66946. // All values and structures referenced from:
  66947. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  66948. var DDS_MAGIC = 0x20534444;
  66949. var
  66950. //DDSD_CAPS = 0x1,
  66951. //DDSD_HEIGHT = 0x2,
  66952. //DDSD_WIDTH = 0x4,
  66953. //DDSD_PITCH = 0x8,
  66954. //DDSD_PIXELFORMAT = 0x1000,
  66955. DDSD_MIPMAPCOUNT = 0x20000;
  66956. //DDSD_LINEARSIZE = 0x80000,
  66957. //DDSD_DEPTH = 0x800000;
  66958. // var DDSCAPS_COMPLEX = 0x8,
  66959. // DDSCAPS_MIPMAP = 0x400000,
  66960. // DDSCAPS_TEXTURE = 0x1000;
  66961. var DDSCAPS2_CUBEMAP = 0x200;
  66962. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  66963. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  66964. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  66965. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  66966. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  66967. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  66968. // DDSCAPS2_VOLUME = 0x200000;
  66969. var
  66970. //DDPF_ALPHAPIXELS = 0x1,
  66971. //DDPF_ALPHA = 0x2,
  66972. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  66973. //DDPF_YUV = 0x200,
  66974. DDPF_LUMINANCE = 0x20000;
  66975. function FourCCToInt32(value) {
  66976. return value.charCodeAt(0) +
  66977. (value.charCodeAt(1) << 8) +
  66978. (value.charCodeAt(2) << 16) +
  66979. (value.charCodeAt(3) << 24);
  66980. }
  66981. function Int32ToFourCC(value) {
  66982. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  66983. }
  66984. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  66985. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  66986. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  66987. var FOURCC_DX10 = FourCCToInt32("DX10");
  66988. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  66989. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  66990. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  66991. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  66992. var headerLengthInt = 31; // The header length in 32 bit ints
  66993. // Offsets into the header array
  66994. var off_magic = 0;
  66995. var off_size = 1;
  66996. var off_flags = 2;
  66997. var off_height = 3;
  66998. var off_width = 4;
  66999. var off_mipmapCount = 7;
  67000. var off_pfFlags = 20;
  67001. var off_pfFourCC = 21;
  67002. var off_RGBbpp = 22;
  67003. // var off_RMask = 23;
  67004. // var off_GMask = 24;
  67005. // var off_BMask = 25;
  67006. // var off_AMask = 26;
  67007. // var off_caps1 = 27;
  67008. var off_caps2 = 28;
  67009. // var off_caps3 = 29;
  67010. // var off_caps4 = 30;
  67011. var off_dxgiFormat = 32;
  67012. ;
  67013. var DDSTools = /** @class */ (function () {
  67014. function DDSTools() {
  67015. }
  67016. DDSTools.GetDDSInfo = function (arrayBuffer) {
  67017. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  67018. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  67019. var mipmapCount = 1;
  67020. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  67021. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67022. }
  67023. var fourCC = header[off_pfFourCC];
  67024. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  67025. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67026. switch (fourCC) {
  67027. case FOURCC_D3DFMT_R16G16B16A16F:
  67028. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67029. break;
  67030. case FOURCC_D3DFMT_R32G32B32A32F:
  67031. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67032. break;
  67033. case FOURCC_DX10:
  67034. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  67035. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67036. break;
  67037. }
  67038. }
  67039. return {
  67040. width: header[off_width],
  67041. height: header[off_height],
  67042. mipmapCount: mipmapCount,
  67043. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  67044. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  67045. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  67046. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  67047. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  67048. dxgiFormat: dxgiFormat,
  67049. textureType: textureType
  67050. };
  67051. };
  67052. DDSTools._ToHalfFloat = function (value) {
  67053. if (!DDSTools._FloatView) {
  67054. DDSTools._FloatView = new Float32Array(1);
  67055. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  67056. }
  67057. DDSTools._FloatView[0] = value;
  67058. var x = DDSTools._Int32View[0];
  67059. var bits = (x >> 16) & 0x8000; /* Get the sign */
  67060. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  67061. var e = (x >> 23) & 0xff; /* Using int is faster here */
  67062. /* If zero, or denormal, or exponent underflows too much for a denormal
  67063. * half, return signed zero. */
  67064. if (e < 103) {
  67065. return bits;
  67066. }
  67067. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  67068. if (e > 142) {
  67069. bits |= 0x7c00;
  67070. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  67071. * not Inf, so make sure we set one mantissa bit too. */
  67072. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  67073. return bits;
  67074. }
  67075. /* If exponent underflows but not too much, return a denormal */
  67076. if (e < 113) {
  67077. m |= 0x0800;
  67078. /* Extra rounding may overflow and set mantissa to 0 and exponent
  67079. * to 1, which is OK. */
  67080. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  67081. return bits;
  67082. }
  67083. bits |= ((e - 112) << 10) | (m >> 1);
  67084. bits += m & 1;
  67085. return bits;
  67086. };
  67087. DDSTools._FromHalfFloat = function (value) {
  67088. var s = (value & 0x8000) >> 15;
  67089. var e = (value & 0x7C00) >> 10;
  67090. var f = value & 0x03FF;
  67091. if (e === 0) {
  67092. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  67093. }
  67094. else if (e == 0x1F) {
  67095. return f ? NaN : ((s ? -1 : 1) * Infinity);
  67096. }
  67097. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  67098. };
  67099. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67100. var destArray = new Float32Array(dataLength);
  67101. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67102. var index = 0;
  67103. for (var y = 0; y < height; y++) {
  67104. for (var x = 0; x < width; x++) {
  67105. var srcPos = (x + y * width) * 4;
  67106. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  67107. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  67108. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  67109. if (DDSTools.StoreLODInAlphaChannel) {
  67110. destArray[index + 3] = lod;
  67111. }
  67112. else {
  67113. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  67114. }
  67115. index += 4;
  67116. }
  67117. }
  67118. return destArray;
  67119. };
  67120. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67121. if (DDSTools.StoreLODInAlphaChannel) {
  67122. var destArray = new Uint16Array(dataLength);
  67123. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67124. var index = 0;
  67125. for (var y = 0; y < height; y++) {
  67126. for (var x = 0; x < width; x++) {
  67127. var srcPos = (x + y * width) * 4;
  67128. destArray[index] = srcData[srcPos];
  67129. destArray[index + 1] = srcData[srcPos + 1];
  67130. destArray[index + 2] = srcData[srcPos + 2];
  67131. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  67132. index += 4;
  67133. }
  67134. }
  67135. return destArray;
  67136. }
  67137. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  67138. };
  67139. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67140. if (DDSTools.StoreLODInAlphaChannel) {
  67141. var destArray = new Float32Array(dataLength);
  67142. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67143. var index = 0;
  67144. for (var y = 0; y < height; y++) {
  67145. for (var x = 0; x < width; x++) {
  67146. var srcPos = (x + y * width) * 4;
  67147. destArray[index] = srcData[srcPos];
  67148. destArray[index + 1] = srcData[srcPos + 1];
  67149. destArray[index + 2] = srcData[srcPos + 2];
  67150. destArray[index + 3] = lod;
  67151. index += 4;
  67152. }
  67153. }
  67154. return destArray;
  67155. }
  67156. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  67157. };
  67158. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67159. var destArray = new Uint8Array(dataLength);
  67160. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67161. var index = 0;
  67162. for (var y = 0; y < height; y++) {
  67163. for (var x = 0; x < width; x++) {
  67164. var srcPos = (x + y * width) * 4;
  67165. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  67166. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  67167. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  67168. if (DDSTools.StoreLODInAlphaChannel) {
  67169. destArray[index + 3] = lod;
  67170. }
  67171. else {
  67172. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  67173. }
  67174. index += 4;
  67175. }
  67176. }
  67177. return destArray;
  67178. };
  67179. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67180. var destArray = new Uint8Array(dataLength);
  67181. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67182. var index = 0;
  67183. for (var y = 0; y < height; y++) {
  67184. for (var x = 0; x < width; x++) {
  67185. var srcPos = (x + y * width) * 4;
  67186. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  67187. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  67188. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  67189. if (DDSTools.StoreLODInAlphaChannel) {
  67190. destArray[index + 3] = lod;
  67191. }
  67192. else {
  67193. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  67194. }
  67195. index += 4;
  67196. }
  67197. }
  67198. return destArray;
  67199. };
  67200. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67201. var byteArray = new Uint8Array(dataLength);
  67202. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67203. var index = 0;
  67204. for (var y = 0; y < height; y++) {
  67205. for (var x = 0; x < width; x++) {
  67206. var srcPos = (x + y * width) * 4;
  67207. byteArray[index] = srcData[srcPos + 2];
  67208. byteArray[index + 1] = srcData[srcPos + 1];
  67209. byteArray[index + 2] = srcData[srcPos];
  67210. byteArray[index + 3] = srcData[srcPos + 3];
  67211. index += 4;
  67212. }
  67213. }
  67214. return byteArray;
  67215. };
  67216. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67217. var byteArray = new Uint8Array(dataLength);
  67218. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67219. var index = 0;
  67220. for (var y = 0; y < height; y++) {
  67221. for (var x = 0; x < width; x++) {
  67222. var srcPos = (x + y * width) * 3;
  67223. byteArray[index] = srcData[srcPos + 2];
  67224. byteArray[index + 1] = srcData[srcPos + 1];
  67225. byteArray[index + 2] = srcData[srcPos];
  67226. index += 3;
  67227. }
  67228. }
  67229. return byteArray;
  67230. };
  67231. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67232. var byteArray = new Uint8Array(dataLength);
  67233. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67234. var index = 0;
  67235. for (var y = 0; y < height; y++) {
  67236. for (var x = 0; x < width; x++) {
  67237. var srcPos = (x + y * width);
  67238. byteArray[index] = srcData[srcPos];
  67239. index++;
  67240. }
  67241. }
  67242. return byteArray;
  67243. };
  67244. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  67245. if (lodIndex === void 0) { lodIndex = -1; }
  67246. var ext = engine.getCaps().s3tc;
  67247. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  67248. var internalFormat = 0;
  67249. var format = 0;
  67250. var blockBytes = 1;
  67251. if (header[off_magic] != DDS_MAGIC) {
  67252. BABYLON.Tools.Error("Invalid magic number in DDS header");
  67253. return;
  67254. }
  67255. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  67256. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  67257. return;
  67258. }
  67259. if (info.isCompressed && !ext) {
  67260. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  67261. return;
  67262. }
  67263. var bpp = header[off_RGBbpp];
  67264. dataOffset = header[off_size] + 4;
  67265. var computeFormats = false;
  67266. if (info.isFourCC) {
  67267. fourCC = header[off_pfFourCC];
  67268. switch (fourCC) {
  67269. case FOURCC_DXT1:
  67270. blockBytes = 8;
  67271. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  67272. break;
  67273. case FOURCC_DXT3:
  67274. blockBytes = 16;
  67275. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  67276. break;
  67277. case FOURCC_DXT5:
  67278. blockBytes = 16;
  67279. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  67280. break;
  67281. case FOURCC_D3DFMT_R16G16B16A16F:
  67282. computeFormats = true;
  67283. break;
  67284. case FOURCC_D3DFMT_R32G32B32A32F:
  67285. computeFormats = true;
  67286. break;
  67287. case FOURCC_DX10:
  67288. // There is an additionnal header so dataOffset need to be changed
  67289. dataOffset += 5 * 4; // 5 uints
  67290. var supported = false;
  67291. switch (info.dxgiFormat) {
  67292. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  67293. computeFormats = true;
  67294. supported = true;
  67295. break;
  67296. case DXGI_FORMAT_B8G8R8X8_UNORM:
  67297. info.isRGB = true;
  67298. info.isFourCC = false;
  67299. bpp = 32;
  67300. supported = true;
  67301. break;
  67302. }
  67303. if (supported) {
  67304. break;
  67305. }
  67306. default:
  67307. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  67308. return;
  67309. }
  67310. }
  67311. if (computeFormats) {
  67312. format = engine._getWebGLTextureType(info.textureType);
  67313. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67314. }
  67315. mipmapCount = 1;
  67316. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  67317. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67318. }
  67319. for (var face = 0; face < faces; face++) {
  67320. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67321. width = header[off_width];
  67322. height = header[off_height];
  67323. for (mip = 0; mip < mipmapCount; ++mip) {
  67324. if (lodIndex === -1 || lodIndex === mip) {
  67325. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  67326. var i = (lodIndex === -1) ? mip : 0;
  67327. if (!info.isCompressed && info.isFourCC) {
  67328. dataLength = width * height * 4;
  67329. var FloatArray = null;
  67330. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  67331. if (bpp === 128) {
  67332. FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67333. }
  67334. else if (bpp === 64) {
  67335. FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67336. }
  67337. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67338. format = engine._getWebGLTextureType(info.textureType);
  67339. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67340. }
  67341. else {
  67342. if (bpp === 128) {
  67343. FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67344. }
  67345. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  67346. FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67347. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67348. format = engine._getWebGLTextureType(info.textureType);
  67349. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67350. }
  67351. else {
  67352. FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67353. }
  67354. }
  67355. if (FloatArray) {
  67356. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray);
  67357. }
  67358. }
  67359. else if (info.isRGB) {
  67360. if (bpp === 24) {
  67361. dataLength = width * height * 3;
  67362. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67363. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  67364. }
  67365. else {
  67366. dataLength = width * height * 4;
  67367. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67368. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  67369. }
  67370. }
  67371. else if (info.isLuminance) {
  67372. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  67373. var unpaddedRowSize = width;
  67374. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  67375. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  67376. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67377. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  67378. }
  67379. else {
  67380. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  67381. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  67382. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  67383. }
  67384. }
  67385. dataOffset += width * height * (bpp / 8);
  67386. width *= 0.5;
  67387. height *= 0.5;
  67388. width = Math.max(1.0, width);
  67389. height = Math.max(1.0, height);
  67390. }
  67391. }
  67392. };
  67393. DDSTools.StoreLODInAlphaChannel = false;
  67394. return DDSTools;
  67395. }());
  67396. Internals.DDSTools = DDSTools;
  67397. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67398. })(BABYLON || (BABYLON = {}));
  67399. //# sourceMappingURL=babylon.dds.js.map
  67400. var BABYLON;
  67401. (function (BABYLON) {
  67402. var Internals;
  67403. (function (Internals) {
  67404. /**
  67405. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  67406. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  67407. */
  67408. var KhronosTextureContainer = /** @class */ (function () {
  67409. /**
  67410. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  67411. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  67412. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  67413. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  67414. */
  67415. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  67416. this.arrayBuffer = arrayBuffer;
  67417. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  67418. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  67419. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  67420. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  67421. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  67422. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  67423. BABYLON.Tools.Error("texture missing KTX identifier");
  67424. return;
  67425. }
  67426. // load the reset of the header in native 32 bit int
  67427. var header = new Int32Array(this.arrayBuffer, 12, 13);
  67428. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  67429. var oppositeEndianess = header[0] === 0x01020304;
  67430. // read all the header elements in order they exist in the file, without modification (sans endainness)
  67431. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  67432. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  67433. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  67434. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  67435. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  67436. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  67437. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  67438. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  67439. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  67440. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  67441. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  67442. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  67443. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  67444. if (this.glType !== 0) {
  67445. BABYLON.Tools.Error("only compressed formats currently supported");
  67446. return;
  67447. }
  67448. else {
  67449. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  67450. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  67451. }
  67452. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  67453. BABYLON.Tools.Error("only 2D textures currently supported");
  67454. return;
  67455. }
  67456. if (this.numberOfArrayElements !== 0) {
  67457. BABYLON.Tools.Error("texture arrays not currently supported");
  67458. return;
  67459. }
  67460. if (this.numberOfFaces !== facesExpected) {
  67461. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  67462. return;
  67463. }
  67464. // we now have a completely validated file, so could use existence of loadType as success
  67465. // would need to make this more elaborate & adjust checks above to support more than one load type
  67466. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  67467. }
  67468. // not as fast hardware based, but will probably never need to use
  67469. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  67470. return ((val & 0xFF) << 24)
  67471. | ((val & 0xFF00) << 8)
  67472. | ((val >> 8) & 0xFF00)
  67473. | ((val >> 24) & 0xFF);
  67474. };
  67475. /**
  67476. * It is assumed that the texture has already been created & is currently bound
  67477. */
  67478. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  67479. switch (this.loadType) {
  67480. case KhronosTextureContainer.COMPRESSED_2D:
  67481. this._upload2DCompressedLevels(gl, loadMipmaps);
  67482. break;
  67483. case KhronosTextureContainer.TEX_2D:
  67484. case KhronosTextureContainer.COMPRESSED_3D:
  67485. case KhronosTextureContainer.TEX_3D:
  67486. }
  67487. };
  67488. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  67489. // initialize width & height for level 1
  67490. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  67491. var width = this.pixelWidth;
  67492. var height = this.pixelHeight;
  67493. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  67494. for (var level = 0; level < mipmapCount; level++) {
  67495. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  67496. for (var face = 0; face < this.numberOfFaces; face++) {
  67497. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67498. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  67499. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  67500. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  67501. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  67502. }
  67503. width = Math.max(1.0, width * 0.5);
  67504. height = Math.max(1.0, height * 0.5);
  67505. }
  67506. };
  67507. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  67508. // load types
  67509. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  67510. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  67511. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  67512. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  67513. return KhronosTextureContainer;
  67514. }());
  67515. Internals.KhronosTextureContainer = KhronosTextureContainer;
  67516. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67517. })(BABYLON || (BABYLON = {}));
  67518. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  67519. var BABYLON;
  67520. (function (BABYLON) {
  67521. var Debug;
  67522. (function (Debug) {
  67523. /**
  67524. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  67525. */
  67526. var SkeletonViewer = /** @class */ (function () {
  67527. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  67528. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  67529. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  67530. this.skeleton = skeleton;
  67531. this.mesh = mesh;
  67532. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  67533. this.renderingGroupId = renderingGroupId;
  67534. this.color = BABYLON.Color3.White();
  67535. this._debugLines = new Array();
  67536. this._isEnabled = false;
  67537. this._scene = scene;
  67538. this.update();
  67539. this._renderFunction = this.update.bind(this);
  67540. }
  67541. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  67542. get: function () {
  67543. return this._isEnabled;
  67544. },
  67545. set: function (value) {
  67546. if (this._isEnabled === value) {
  67547. return;
  67548. }
  67549. this._isEnabled = value;
  67550. if (value) {
  67551. this._scene.registerBeforeRender(this._renderFunction);
  67552. }
  67553. else {
  67554. this._scene.unregisterBeforeRender(this._renderFunction);
  67555. }
  67556. },
  67557. enumerable: true,
  67558. configurable: true
  67559. });
  67560. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  67561. if (x === void 0) { x = 0; }
  67562. if (y === void 0) { y = 0; }
  67563. if (z === void 0) { z = 0; }
  67564. var tmat = BABYLON.Tmp.Matrix[0];
  67565. var parentBone = bone.getParent();
  67566. tmat.copyFrom(bone.getLocalMatrix());
  67567. if (x !== 0 || y !== 0 || z !== 0) {
  67568. var tmat2 = BABYLON.Tmp.Matrix[1];
  67569. BABYLON.Matrix.IdentityToRef(tmat2);
  67570. tmat2.m[12] = x;
  67571. tmat2.m[13] = y;
  67572. tmat2.m[14] = z;
  67573. tmat2.multiplyToRef(tmat, tmat);
  67574. }
  67575. if (parentBone) {
  67576. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  67577. }
  67578. tmat.multiplyToRef(meshMat, tmat);
  67579. position.x = tmat.m[12];
  67580. position.y = tmat.m[13];
  67581. position.z = tmat.m[14];
  67582. };
  67583. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  67584. var len = bones.length;
  67585. var meshPos = this.mesh.position;
  67586. for (var i = 0; i < len; i++) {
  67587. var bone = bones[i];
  67588. var points = this._debugLines[i];
  67589. if (!points) {
  67590. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67591. this._debugLines[i] = points;
  67592. }
  67593. this._getBonePosition(points[0], bone, meshMat);
  67594. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  67595. points[0].subtractInPlace(meshPos);
  67596. points[1].subtractInPlace(meshPos);
  67597. }
  67598. };
  67599. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  67600. var len = bones.length;
  67601. var boneNum = 0;
  67602. var meshPos = this.mesh.position;
  67603. for (var i = len - 1; i >= 0; i--) {
  67604. var childBone = bones[i];
  67605. var parentBone = childBone.getParent();
  67606. if (!parentBone) {
  67607. continue;
  67608. }
  67609. var points = this._debugLines[boneNum];
  67610. if (!points) {
  67611. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67612. this._debugLines[boneNum] = points;
  67613. }
  67614. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  67615. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  67616. points[0].subtractInPlace(meshPos);
  67617. points[1].subtractInPlace(meshPos);
  67618. boneNum++;
  67619. }
  67620. };
  67621. SkeletonViewer.prototype.update = function () {
  67622. if (this.autoUpdateBonesMatrices) {
  67623. this.skeleton.computeAbsoluteTransforms();
  67624. }
  67625. if (this.skeleton.bones[0].length === undefined) {
  67626. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67627. }
  67628. else {
  67629. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67630. }
  67631. if (!this._debugMesh) {
  67632. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  67633. this._debugMesh.renderingGroupId = this.renderingGroupId;
  67634. }
  67635. else {
  67636. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  67637. }
  67638. this._debugMesh.position.copyFrom(this.mesh.position);
  67639. this._debugMesh.color = this.color;
  67640. };
  67641. SkeletonViewer.prototype.dispose = function () {
  67642. if (this._debugMesh) {
  67643. this.isEnabled = false;
  67644. this._debugMesh.dispose();
  67645. this._debugMesh = null;
  67646. }
  67647. };
  67648. return SkeletonViewer;
  67649. }());
  67650. Debug.SkeletonViewer = SkeletonViewer;
  67651. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67652. })(BABYLON || (BABYLON = {}));
  67653. //# sourceMappingURL=babylon.skeletonViewer.js.map
  67654. var BABYLON;
  67655. (function (BABYLON) {
  67656. var Debug;
  67657. (function (Debug) {
  67658. var AxesViewer = /** @class */ (function () {
  67659. function AxesViewer(scene, scaleLines) {
  67660. if (scaleLines === void 0) { scaleLines = 1; }
  67661. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67662. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67663. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67664. this.scaleLines = 1;
  67665. this.scaleLines = scaleLines;
  67666. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  67667. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  67668. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  67669. this._xmesh.renderingGroupId = 2;
  67670. this._ymesh.renderingGroupId = 2;
  67671. this._zmesh.renderingGroupId = 2;
  67672. this._xmesh.material.checkReadyOnlyOnce = true;
  67673. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  67674. this._ymesh.material.checkReadyOnlyOnce = true;
  67675. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  67676. this._zmesh.material.checkReadyOnlyOnce = true;
  67677. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  67678. this.scene = scene;
  67679. }
  67680. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  67681. var scaleLines = this.scaleLines;
  67682. if (this._xmesh) {
  67683. this._xmesh.position.copyFrom(position);
  67684. }
  67685. if (this._ymesh) {
  67686. this._ymesh.position.copyFrom(position);
  67687. }
  67688. if (this._zmesh) {
  67689. this._zmesh.position.copyFrom(position);
  67690. }
  67691. var point2 = this._xline[1];
  67692. point2.x = xaxis.x * scaleLines;
  67693. point2.y = xaxis.y * scaleLines;
  67694. point2.z = xaxis.z * scaleLines;
  67695. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  67696. point2 = this._yline[1];
  67697. point2.x = yaxis.x * scaleLines;
  67698. point2.y = yaxis.y * scaleLines;
  67699. point2.z = yaxis.z * scaleLines;
  67700. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  67701. point2 = this._zline[1];
  67702. point2.x = zaxis.x * scaleLines;
  67703. point2.y = zaxis.y * scaleLines;
  67704. point2.z = zaxis.z * scaleLines;
  67705. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  67706. };
  67707. AxesViewer.prototype.dispose = function () {
  67708. if (this._xmesh) {
  67709. this._xmesh.dispose();
  67710. }
  67711. if (this._ymesh) {
  67712. this._ymesh.dispose();
  67713. }
  67714. if (this._zmesh) {
  67715. this._zmesh.dispose();
  67716. }
  67717. this._xmesh = null;
  67718. this._ymesh = null;
  67719. this._zmesh = null;
  67720. this.scene = null;
  67721. };
  67722. return AxesViewer;
  67723. }());
  67724. Debug.AxesViewer = AxesViewer;
  67725. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67726. })(BABYLON || (BABYLON = {}));
  67727. //# sourceMappingURL=babylon.axesViewer.js.map
  67728. var BABYLON;
  67729. (function (BABYLON) {
  67730. var Debug;
  67731. (function (Debug) {
  67732. var BoneAxesViewer = /** @class */ (function (_super) {
  67733. __extends(BoneAxesViewer, _super);
  67734. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  67735. if (scaleLines === void 0) { scaleLines = 1; }
  67736. var _this = _super.call(this, scene, scaleLines) || this;
  67737. _this.pos = BABYLON.Vector3.Zero();
  67738. _this.xaxis = BABYLON.Vector3.Zero();
  67739. _this.yaxis = BABYLON.Vector3.Zero();
  67740. _this.zaxis = BABYLON.Vector3.Zero();
  67741. _this.mesh = mesh;
  67742. _this.bone = bone;
  67743. return _this;
  67744. }
  67745. BoneAxesViewer.prototype.update = function () {
  67746. if (!this.mesh || !this.bone) {
  67747. return;
  67748. }
  67749. var bone = this.bone;
  67750. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  67751. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  67752. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  67753. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  67754. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  67755. };
  67756. BoneAxesViewer.prototype.dispose = function () {
  67757. if (this.mesh) {
  67758. this.mesh = null;
  67759. this.bone = null;
  67760. _super.prototype.dispose.call(this);
  67761. }
  67762. };
  67763. return BoneAxesViewer;
  67764. }(Debug.AxesViewer));
  67765. Debug.BoneAxesViewer = BoneAxesViewer;
  67766. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67767. })(BABYLON || (BABYLON = {}));
  67768. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  67769. var BABYLON;
  67770. (function (BABYLON) {
  67771. var RayHelper = /** @class */ (function () {
  67772. function RayHelper(ray) {
  67773. this.ray = ray;
  67774. }
  67775. RayHelper.CreateAndShow = function (ray, scene, color) {
  67776. var helper = new RayHelper(ray);
  67777. helper.show(scene, color);
  67778. return helper;
  67779. };
  67780. RayHelper.prototype.show = function (scene, color) {
  67781. if (!this._renderFunction && this.ray) {
  67782. var ray = this.ray;
  67783. this._renderFunction = this._render.bind(this);
  67784. this._scene = scene;
  67785. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  67786. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  67787. if (this._renderFunction) {
  67788. this._scene.registerBeforeRender(this._renderFunction);
  67789. }
  67790. }
  67791. if (color && this._renderLine) {
  67792. this._renderLine.color.copyFrom(color);
  67793. }
  67794. };
  67795. RayHelper.prototype.hide = function () {
  67796. if (this._renderFunction && this._scene) {
  67797. this._scene.unregisterBeforeRender(this._renderFunction);
  67798. this._scene = null;
  67799. this._renderFunction = null;
  67800. if (this._renderLine) {
  67801. this._renderLine.dispose();
  67802. this._renderLine = null;
  67803. }
  67804. this._renderPoints = [];
  67805. }
  67806. };
  67807. RayHelper.prototype._render = function () {
  67808. var ray = this.ray;
  67809. if (!ray) {
  67810. return;
  67811. }
  67812. var point = this._renderPoints[1];
  67813. var len = Math.min(ray.length, 1000000);
  67814. point.copyFrom(ray.direction);
  67815. point.scaleInPlace(len);
  67816. point.addInPlace(ray.origin);
  67817. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  67818. };
  67819. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  67820. this._attachedToMesh = mesh;
  67821. var ray = this.ray;
  67822. if (!ray) {
  67823. return;
  67824. }
  67825. if (!ray.direction) {
  67826. ray.direction = BABYLON.Vector3.Zero();
  67827. }
  67828. if (!ray.origin) {
  67829. ray.origin = BABYLON.Vector3.Zero();
  67830. }
  67831. if (length) {
  67832. ray.length = length;
  67833. }
  67834. if (!meshSpaceOrigin) {
  67835. meshSpaceOrigin = BABYLON.Vector3.Zero();
  67836. }
  67837. if (!meshSpaceDirection) {
  67838. // -1 so that this will work with Mesh.lookAt
  67839. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  67840. }
  67841. if (!this._meshSpaceDirection) {
  67842. this._meshSpaceDirection = meshSpaceDirection.clone();
  67843. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  67844. }
  67845. else {
  67846. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  67847. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  67848. }
  67849. if (!this._updateToMeshFunction) {
  67850. this._updateToMeshFunction = this._updateToMesh.bind(this);
  67851. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  67852. }
  67853. this._updateToMesh();
  67854. };
  67855. RayHelper.prototype.detachFromMesh = function () {
  67856. if (this._attachedToMesh) {
  67857. if (this._updateToMeshFunction) {
  67858. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  67859. }
  67860. this._attachedToMesh = null;
  67861. this._updateToMeshFunction = null;
  67862. }
  67863. };
  67864. RayHelper.prototype._updateToMesh = function () {
  67865. var ray = this.ray;
  67866. if (!this._attachedToMesh || !ray) {
  67867. return;
  67868. }
  67869. if (this._attachedToMesh._isDisposed) {
  67870. this.detachFromMesh();
  67871. return;
  67872. }
  67873. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  67874. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  67875. };
  67876. RayHelper.prototype.dispose = function () {
  67877. this.hide();
  67878. this.detachFromMesh();
  67879. this.ray = null;
  67880. };
  67881. return RayHelper;
  67882. }());
  67883. BABYLON.RayHelper = RayHelper;
  67884. })(BABYLON || (BABYLON = {}));
  67885. //# sourceMappingURL=babylon.rayHelper.js.map
  67886. var BABYLON;
  67887. (function (BABYLON) {
  67888. var DebugLayer = /** @class */ (function () {
  67889. function DebugLayer(scene) {
  67890. this._scene = scene;
  67891. }
  67892. /** Creates the inspector window. */
  67893. DebugLayer.prototype._createInspector = function (config) {
  67894. if (config === void 0) { config = {}; }
  67895. var popup = config.popup || false;
  67896. var initialTab = config.initialTab || 0;
  67897. var parentElement = config.parentElement || null;
  67898. if (!this._inspector) {
  67899. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  67900. } // else nothing to do,; instance is already existing
  67901. };
  67902. DebugLayer.prototype.isVisible = function () {
  67903. if (!this._inspector) {
  67904. return false;
  67905. }
  67906. return true;
  67907. };
  67908. DebugLayer.prototype.hide = function () {
  67909. if (this._inspector) {
  67910. try {
  67911. this._inspector.dispose();
  67912. }
  67913. catch (e) {
  67914. // If the inspector has been removed directly from the inspector tool
  67915. }
  67916. this._inspector = null;
  67917. }
  67918. };
  67919. DebugLayer.prototype.show = function (config) {
  67920. if (config === void 0) { config = {}; }
  67921. if (typeof INSPECTOR == 'undefined') {
  67922. // Load inspector and add it to the DOM
  67923. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  67924. }
  67925. else {
  67926. // Otherwise creates the inspector
  67927. this._createInspector(config);
  67928. }
  67929. };
  67930. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  67931. return DebugLayer;
  67932. }());
  67933. BABYLON.DebugLayer = DebugLayer;
  67934. })(BABYLON || (BABYLON = {}));
  67935. //# sourceMappingURL=babylon.debugLayer.js.map
  67936. var BABYLON;
  67937. (function (BABYLON) {
  67938. var Debug;
  67939. (function (Debug) {
  67940. var PhysicsViewer = /** @class */ (function () {
  67941. function PhysicsViewer(scene) {
  67942. this._impostors = [];
  67943. this._meshes = [];
  67944. this._numMeshes = 0;
  67945. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67946. var physicEngine = this._scene.getPhysicsEngine();
  67947. if (physicEngine) {
  67948. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  67949. }
  67950. }
  67951. PhysicsViewer.prototype._updateDebugMeshes = function () {
  67952. var plugin = this._physicsEnginePlugin;
  67953. for (var i = 0; i < this._numMeshes; i++) {
  67954. var impostor = this._impostors[i];
  67955. if (!impostor) {
  67956. continue;
  67957. }
  67958. if (impostor.isDisposed) {
  67959. this.hideImpostor(this._impostors[i--]);
  67960. }
  67961. else {
  67962. var mesh = this._meshes[i];
  67963. if (mesh && plugin) {
  67964. plugin.syncMeshWithImpostor(mesh, impostor);
  67965. }
  67966. }
  67967. }
  67968. };
  67969. PhysicsViewer.prototype.showImpostor = function (impostor) {
  67970. if (!this._scene) {
  67971. return;
  67972. }
  67973. for (var i = 0; i < this._numMeshes; i++) {
  67974. if (this._impostors[i] == impostor) {
  67975. return;
  67976. }
  67977. }
  67978. var debugMesh = this._getDebugMesh(impostor, this._scene);
  67979. if (debugMesh) {
  67980. this._impostors[this._numMeshes] = impostor;
  67981. this._meshes[this._numMeshes] = debugMesh;
  67982. if (this._numMeshes === 0) {
  67983. this._renderFunction = this._updateDebugMeshes.bind(this);
  67984. this._scene.registerBeforeRender(this._renderFunction);
  67985. }
  67986. this._numMeshes++;
  67987. }
  67988. };
  67989. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  67990. if (!impostor || !this._scene) {
  67991. return;
  67992. }
  67993. var removed = false;
  67994. for (var i = 0; i < this._numMeshes; i++) {
  67995. if (this._impostors[i] == impostor) {
  67996. var mesh = this._meshes[i];
  67997. if (!mesh) {
  67998. continue;
  67999. }
  68000. this._scene.removeMesh(mesh);
  68001. mesh.dispose();
  68002. this._numMeshes--;
  68003. if (this._numMeshes > 0) {
  68004. this._meshes[i] = this._meshes[this._numMeshes];
  68005. this._impostors[i] = this._impostors[this._numMeshes];
  68006. this._meshes[this._numMeshes] = null;
  68007. this._impostors[this._numMeshes] = null;
  68008. }
  68009. else {
  68010. this._meshes[0] = null;
  68011. this._impostors[0] = null;
  68012. }
  68013. removed = true;
  68014. break;
  68015. }
  68016. }
  68017. if (removed && this._numMeshes === 0) {
  68018. this._scene.unregisterBeforeRender(this._renderFunction);
  68019. }
  68020. };
  68021. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  68022. if (!this._debugMaterial) {
  68023. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  68024. this._debugMaterial.wireframe = true;
  68025. }
  68026. return this._debugMaterial;
  68027. };
  68028. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  68029. if (!this._debugBoxMesh) {
  68030. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  68031. this._debugBoxMesh.renderingGroupId = 1;
  68032. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68033. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  68034. scene.removeMesh(this._debugBoxMesh);
  68035. }
  68036. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  68037. };
  68038. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  68039. if (!this._debugSphereMesh) {
  68040. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  68041. this._debugSphereMesh.renderingGroupId = 1;
  68042. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68043. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  68044. scene.removeMesh(this._debugSphereMesh);
  68045. }
  68046. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  68047. };
  68048. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  68049. var mesh = null;
  68050. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  68051. mesh = this._getDebugBoxMesh(scene);
  68052. impostor.getBoxSizeToRef(mesh.scaling);
  68053. }
  68054. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  68055. mesh = this._getDebugSphereMesh(scene);
  68056. var radius = impostor.getRadius();
  68057. mesh.scaling.x = radius * 2;
  68058. mesh.scaling.y = radius * 2;
  68059. mesh.scaling.z = radius * 2;
  68060. }
  68061. return mesh;
  68062. };
  68063. PhysicsViewer.prototype.dispose = function () {
  68064. for (var i = 0; i < this._numMeshes; i++) {
  68065. this.hideImpostor(this._impostors[i]);
  68066. }
  68067. if (this._debugBoxMesh) {
  68068. this._debugBoxMesh.dispose();
  68069. }
  68070. if (this._debugSphereMesh) {
  68071. this._debugSphereMesh.dispose();
  68072. }
  68073. if (this._debugMaterial) {
  68074. this._debugMaterial.dispose();
  68075. }
  68076. this._impostors.length = 0;
  68077. this._scene = null;
  68078. this._physicsEnginePlugin = null;
  68079. };
  68080. return PhysicsViewer;
  68081. }());
  68082. Debug.PhysicsViewer = PhysicsViewer;
  68083. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68084. })(BABYLON || (BABYLON = {}));
  68085. //# sourceMappingURL=babylon.physicsViewer.js.map
  68086. var BABYLON;
  68087. (function (BABYLON) {
  68088. var BoundingBoxRenderer = /** @class */ (function () {
  68089. function BoundingBoxRenderer(scene) {
  68090. this.frontColor = new BABYLON.Color3(1, 1, 1);
  68091. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  68092. this.showBackLines = true;
  68093. this.renderList = new BABYLON.SmartArray(32);
  68094. this._vertexBuffers = {};
  68095. this._scene = scene;
  68096. }
  68097. BoundingBoxRenderer.prototype._prepareRessources = function () {
  68098. if (this._colorShader) {
  68099. return;
  68100. }
  68101. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  68102. attributes: [BABYLON.VertexBuffer.PositionKind],
  68103. uniforms: ["world", "viewProjection", "color"]
  68104. });
  68105. var engine = this._scene.getEngine();
  68106. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  68107. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  68108. this._createIndexBuffer();
  68109. };
  68110. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  68111. var engine = this._scene.getEngine();
  68112. 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]);
  68113. };
  68114. BoundingBoxRenderer.prototype._rebuild = function () {
  68115. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68116. if (vb) {
  68117. vb._rebuild();
  68118. }
  68119. this._createIndexBuffer();
  68120. };
  68121. BoundingBoxRenderer.prototype.reset = function () {
  68122. this.renderList.reset();
  68123. };
  68124. BoundingBoxRenderer.prototype.render = function () {
  68125. if (this.renderList.length === 0) {
  68126. return;
  68127. }
  68128. this._prepareRessources();
  68129. if (!this._colorShader.isReady()) {
  68130. return;
  68131. }
  68132. var engine = this._scene.getEngine();
  68133. engine.setDepthWrite(false);
  68134. this._colorShader._preBind();
  68135. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  68136. var boundingBox = this.renderList.data[boundingBoxIndex];
  68137. var min = boundingBox.minimum;
  68138. var max = boundingBox.maximum;
  68139. var diff = max.subtract(min);
  68140. var median = min.add(diff.scale(0.5));
  68141. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68142. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68143. .multiply(boundingBox.getWorldMatrix());
  68144. // VBOs
  68145. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68146. if (this.showBackLines) {
  68147. // Back
  68148. engine.setDepthFunctionToGreaterOrEqual();
  68149. this._scene.resetCachedMaterial();
  68150. this._colorShader.setColor4("color", this.backColor.toColor4());
  68151. this._colorShader.bind(worldMatrix);
  68152. // Draw order
  68153. engine.draw(false, 0, 24);
  68154. }
  68155. // Front
  68156. engine.setDepthFunctionToLess();
  68157. this._scene.resetCachedMaterial();
  68158. this._colorShader.setColor4("color", this.frontColor.toColor4());
  68159. this._colorShader.bind(worldMatrix);
  68160. // Draw order
  68161. engine.draw(false, 0, 24);
  68162. }
  68163. this._colorShader.unbind();
  68164. engine.setDepthFunctionToLessOrEqual();
  68165. engine.setDepthWrite(true);
  68166. };
  68167. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  68168. this._prepareRessources();
  68169. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  68170. return;
  68171. }
  68172. var engine = this._scene.getEngine();
  68173. engine.setDepthWrite(false);
  68174. engine.setColorWrite(false);
  68175. this._colorShader._preBind();
  68176. var boundingBox = mesh._boundingInfo.boundingBox;
  68177. var min = boundingBox.minimum;
  68178. var max = boundingBox.maximum;
  68179. var diff = max.subtract(min);
  68180. var median = min.add(diff.scale(0.5));
  68181. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68182. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68183. .multiply(boundingBox.getWorldMatrix());
  68184. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68185. engine.setDepthFunctionToLess();
  68186. this._scene.resetCachedMaterial();
  68187. this._colorShader.bind(worldMatrix);
  68188. engine.draw(false, 0, 24);
  68189. this._colorShader.unbind();
  68190. engine.setDepthFunctionToLessOrEqual();
  68191. engine.setDepthWrite(true);
  68192. engine.setColorWrite(true);
  68193. };
  68194. BoundingBoxRenderer.prototype.dispose = function () {
  68195. if (!this._colorShader) {
  68196. return;
  68197. }
  68198. this.renderList.dispose();
  68199. this._colorShader.dispose();
  68200. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68201. if (buffer) {
  68202. buffer.dispose();
  68203. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68204. }
  68205. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68206. };
  68207. return BoundingBoxRenderer;
  68208. }());
  68209. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  68210. })(BABYLON || (BABYLON = {}));
  68211. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  68212. var BABYLON;
  68213. (function (BABYLON) {
  68214. var MorphTarget = /** @class */ (function () {
  68215. function MorphTarget(name, influence) {
  68216. if (influence === void 0) { influence = 0; }
  68217. this.name = name;
  68218. this.animations = new Array();
  68219. this._positions = null;
  68220. this._normals = null;
  68221. this._tangents = null;
  68222. this.onInfluenceChanged = new BABYLON.Observable();
  68223. this.influence = influence;
  68224. }
  68225. Object.defineProperty(MorphTarget.prototype, "influence", {
  68226. get: function () {
  68227. return this._influence;
  68228. },
  68229. set: function (influence) {
  68230. if (this._influence === influence) {
  68231. return;
  68232. }
  68233. var previous = this._influence;
  68234. this._influence = influence;
  68235. if (this.onInfluenceChanged.hasObservers) {
  68236. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  68237. }
  68238. },
  68239. enumerable: true,
  68240. configurable: true
  68241. });
  68242. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  68243. get: function () {
  68244. return !!this._positions;
  68245. },
  68246. enumerable: true,
  68247. configurable: true
  68248. });
  68249. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  68250. get: function () {
  68251. return !!this._normals;
  68252. },
  68253. enumerable: true,
  68254. configurable: true
  68255. });
  68256. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  68257. get: function () {
  68258. return !!this._tangents;
  68259. },
  68260. enumerable: true,
  68261. configurable: true
  68262. });
  68263. MorphTarget.prototype.setPositions = function (data) {
  68264. this._positions = data;
  68265. };
  68266. MorphTarget.prototype.getPositions = function () {
  68267. return this._positions;
  68268. };
  68269. MorphTarget.prototype.setNormals = function (data) {
  68270. this._normals = data;
  68271. };
  68272. MorphTarget.prototype.getNormals = function () {
  68273. return this._normals;
  68274. };
  68275. MorphTarget.prototype.setTangents = function (data) {
  68276. this._tangents = data;
  68277. };
  68278. MorphTarget.prototype.getTangents = function () {
  68279. return this._tangents;
  68280. };
  68281. /**
  68282. * Serializes the current target into a Serialization object.
  68283. * Returns the serialized object.
  68284. */
  68285. MorphTarget.prototype.serialize = function () {
  68286. var serializationObject = {};
  68287. serializationObject.name = this.name;
  68288. serializationObject.influence = this.influence;
  68289. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  68290. if (this.hasNormals) {
  68291. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  68292. }
  68293. if (this.hasTangents) {
  68294. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  68295. }
  68296. // Animations
  68297. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  68298. return serializationObject;
  68299. };
  68300. // Statics
  68301. MorphTarget.Parse = function (serializationObject) {
  68302. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  68303. result.setPositions(serializationObject.positions);
  68304. if (serializationObject.normals) {
  68305. result.setNormals(serializationObject.normals);
  68306. }
  68307. if (serializationObject.tangents) {
  68308. result.setTangents(serializationObject.tangents);
  68309. }
  68310. // Animations
  68311. if (serializationObject.animations) {
  68312. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  68313. var parsedAnimation = serializationObject.animations[animationIndex];
  68314. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  68315. }
  68316. }
  68317. return result;
  68318. };
  68319. MorphTarget.FromMesh = function (mesh, name, influence) {
  68320. if (!name) {
  68321. name = mesh.name;
  68322. }
  68323. var result = new MorphTarget(name, influence);
  68324. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68325. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68326. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  68327. }
  68328. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  68329. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  68330. }
  68331. return result;
  68332. };
  68333. return MorphTarget;
  68334. }());
  68335. BABYLON.MorphTarget = MorphTarget;
  68336. })(BABYLON || (BABYLON = {}));
  68337. //# sourceMappingURL=babylon.morphTarget.js.map
  68338. var BABYLON;
  68339. (function (BABYLON) {
  68340. var MorphTargetManager = /** @class */ (function () {
  68341. function MorphTargetManager(scene) {
  68342. if (scene === void 0) { scene = null; }
  68343. this._targets = new Array();
  68344. this._targetObservable = new Array();
  68345. this._activeTargets = new BABYLON.SmartArray(16);
  68346. this._supportsNormals = false;
  68347. this._supportsTangents = false;
  68348. this._vertexCount = 0;
  68349. this._uniqueId = 0;
  68350. this._tempInfluences = new Array();
  68351. if (!scene) {
  68352. scene = BABYLON.Engine.LastCreatedScene;
  68353. }
  68354. this._scene = scene;
  68355. if (this._scene) {
  68356. this._scene.morphTargetManagers.push(this);
  68357. this._uniqueId = this._scene.getUniqueId();
  68358. }
  68359. }
  68360. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  68361. get: function () {
  68362. return this._uniqueId;
  68363. },
  68364. enumerable: true,
  68365. configurable: true
  68366. });
  68367. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  68368. get: function () {
  68369. return this._vertexCount;
  68370. },
  68371. enumerable: true,
  68372. configurable: true
  68373. });
  68374. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  68375. get: function () {
  68376. return this._supportsNormals;
  68377. },
  68378. enumerable: true,
  68379. configurable: true
  68380. });
  68381. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  68382. get: function () {
  68383. return this._supportsTangents;
  68384. },
  68385. enumerable: true,
  68386. configurable: true
  68387. });
  68388. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  68389. get: function () {
  68390. return this._targets.length;
  68391. },
  68392. enumerable: true,
  68393. configurable: true
  68394. });
  68395. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  68396. get: function () {
  68397. return this._activeTargets.length;
  68398. },
  68399. enumerable: true,
  68400. configurable: true
  68401. });
  68402. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  68403. get: function () {
  68404. return this._influences;
  68405. },
  68406. enumerable: true,
  68407. configurable: true
  68408. });
  68409. MorphTargetManager.prototype.getActiveTarget = function (index) {
  68410. return this._activeTargets.data[index];
  68411. };
  68412. MorphTargetManager.prototype.getTarget = function (index) {
  68413. return this._targets[index];
  68414. };
  68415. MorphTargetManager.prototype.addTarget = function (target) {
  68416. var _this = this;
  68417. this._targets.push(target);
  68418. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  68419. _this._syncActiveTargets(needUpdate);
  68420. }));
  68421. this._syncActiveTargets(true);
  68422. };
  68423. MorphTargetManager.prototype.removeTarget = function (target) {
  68424. var index = this._targets.indexOf(target);
  68425. if (index >= 0) {
  68426. this._targets.splice(index, 1);
  68427. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  68428. this._syncActiveTargets(true);
  68429. }
  68430. };
  68431. /**
  68432. * Serializes the current manager into a Serialization object.
  68433. * Returns the serialized object.
  68434. */
  68435. MorphTargetManager.prototype.serialize = function () {
  68436. var serializationObject = {};
  68437. serializationObject.id = this.uniqueId;
  68438. serializationObject.targets = [];
  68439. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68440. var target = _a[_i];
  68441. serializationObject.targets.push(target.serialize());
  68442. }
  68443. return serializationObject;
  68444. };
  68445. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  68446. var influenceCount = 0;
  68447. this._activeTargets.reset();
  68448. this._supportsNormals = true;
  68449. this._supportsTangents = true;
  68450. this._vertexCount = 0;
  68451. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68452. var target = _a[_i];
  68453. if (target.influence > 0) {
  68454. this._activeTargets.push(target);
  68455. this._tempInfluences[influenceCount++] = target.influence;
  68456. this._supportsNormals = this._supportsNormals && target.hasNormals;
  68457. this._supportsTangents = this._supportsTangents && target.hasTangents;
  68458. var positions = target.getPositions();
  68459. if (!positions) {
  68460. BABYLON.Tools.Error("Invalid target. Target must positions.");
  68461. return;
  68462. }
  68463. var vertexCount = positions.length / 3;
  68464. if (this._vertexCount === 0) {
  68465. this._vertexCount = vertexCount;
  68466. }
  68467. else if (this._vertexCount !== vertexCount) {
  68468. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  68469. return;
  68470. }
  68471. }
  68472. }
  68473. if (!this._influences || this._influences.length !== influenceCount) {
  68474. this._influences = new Float32Array(influenceCount);
  68475. }
  68476. for (var index = 0; index < influenceCount; index++) {
  68477. this._influences[index] = this._tempInfluences[index];
  68478. }
  68479. if (needUpdate && this._scene) {
  68480. // Flag meshes as dirty to resync with the active targets
  68481. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  68482. var mesh = _c[_b];
  68483. if (mesh.morphTargetManager === this) {
  68484. mesh._syncGeometryWithMorphTargetManager();
  68485. }
  68486. }
  68487. }
  68488. };
  68489. // Statics
  68490. MorphTargetManager.Parse = function (serializationObject, scene) {
  68491. var result = new MorphTargetManager(scene);
  68492. result._uniqueId = serializationObject.id;
  68493. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  68494. var targetData = _a[_i];
  68495. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  68496. }
  68497. return result;
  68498. };
  68499. return MorphTargetManager;
  68500. }());
  68501. BABYLON.MorphTargetManager = MorphTargetManager;
  68502. })(BABYLON || (BABYLON = {}));
  68503. //# sourceMappingURL=babylon.morphTargetManager.js.map
  68504. var BABYLON;
  68505. (function (BABYLON) {
  68506. var Octree = /** @class */ (function () {
  68507. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  68508. if (maxDepth === void 0) { maxDepth = 2; }
  68509. this.maxDepth = maxDepth;
  68510. this.dynamicContent = new Array();
  68511. this._maxBlockCapacity = maxBlockCapacity || 64;
  68512. this._selectionContent = new BABYLON.SmartArray(1024);
  68513. this._creationFunc = creationFunc;
  68514. }
  68515. // Methods
  68516. Octree.prototype.update = function (worldMin, worldMax, entries) {
  68517. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  68518. };
  68519. Octree.prototype.addMesh = function (entry) {
  68520. for (var index = 0; index < this.blocks.length; index++) {
  68521. var block = this.blocks[index];
  68522. block.addEntry(entry);
  68523. }
  68524. };
  68525. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  68526. this._selectionContent.reset();
  68527. for (var index = 0; index < this.blocks.length; index++) {
  68528. var block = this.blocks[index];
  68529. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  68530. }
  68531. if (allowDuplicate) {
  68532. this._selectionContent.concat(this.dynamicContent);
  68533. }
  68534. else {
  68535. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68536. }
  68537. return this._selectionContent;
  68538. };
  68539. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  68540. this._selectionContent.reset();
  68541. for (var index = 0; index < this.blocks.length; index++) {
  68542. var block = this.blocks[index];
  68543. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  68544. }
  68545. if (allowDuplicate) {
  68546. this._selectionContent.concat(this.dynamicContent);
  68547. }
  68548. else {
  68549. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68550. }
  68551. return this._selectionContent;
  68552. };
  68553. Octree.prototype.intersectsRay = function (ray) {
  68554. this._selectionContent.reset();
  68555. for (var index = 0; index < this.blocks.length; index++) {
  68556. var block = this.blocks[index];
  68557. block.intersectsRay(ray, this._selectionContent);
  68558. }
  68559. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68560. return this._selectionContent;
  68561. };
  68562. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  68563. target.blocks = new Array();
  68564. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  68565. // Segmenting space
  68566. for (var x = 0; x < 2; x++) {
  68567. for (var y = 0; y < 2; y++) {
  68568. for (var z = 0; z < 2; z++) {
  68569. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  68570. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  68571. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  68572. block.addEntries(entries);
  68573. target.blocks.push(block);
  68574. }
  68575. }
  68576. }
  68577. };
  68578. Octree.CreationFuncForMeshes = function (entry, block) {
  68579. var boundingInfo = entry.getBoundingInfo();
  68580. if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68581. block.entries.push(entry);
  68582. }
  68583. };
  68584. Octree.CreationFuncForSubMeshes = function (entry, block) {
  68585. var boundingInfo = entry.getBoundingInfo();
  68586. if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68587. block.entries.push(entry);
  68588. }
  68589. };
  68590. return Octree;
  68591. }());
  68592. BABYLON.Octree = Octree;
  68593. })(BABYLON || (BABYLON = {}));
  68594. //# sourceMappingURL=babylon.octree.js.map
  68595. var BABYLON;
  68596. (function (BABYLON) {
  68597. var OctreeBlock = /** @class */ (function () {
  68598. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  68599. this.entries = new Array();
  68600. this._boundingVectors = new Array();
  68601. this._capacity = capacity;
  68602. this._depth = depth;
  68603. this._maxDepth = maxDepth;
  68604. this._creationFunc = creationFunc;
  68605. this._minPoint = minPoint;
  68606. this._maxPoint = maxPoint;
  68607. this._boundingVectors.push(minPoint.clone());
  68608. this._boundingVectors.push(maxPoint.clone());
  68609. this._boundingVectors.push(minPoint.clone());
  68610. this._boundingVectors[2].x = maxPoint.x;
  68611. this._boundingVectors.push(minPoint.clone());
  68612. this._boundingVectors[3].y = maxPoint.y;
  68613. this._boundingVectors.push(minPoint.clone());
  68614. this._boundingVectors[4].z = maxPoint.z;
  68615. this._boundingVectors.push(maxPoint.clone());
  68616. this._boundingVectors[5].z = minPoint.z;
  68617. this._boundingVectors.push(maxPoint.clone());
  68618. this._boundingVectors[6].x = minPoint.x;
  68619. this._boundingVectors.push(maxPoint.clone());
  68620. this._boundingVectors[7].y = minPoint.y;
  68621. }
  68622. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  68623. // Property
  68624. get: function () {
  68625. return this._capacity;
  68626. },
  68627. enumerable: true,
  68628. configurable: true
  68629. });
  68630. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  68631. get: function () {
  68632. return this._minPoint;
  68633. },
  68634. enumerable: true,
  68635. configurable: true
  68636. });
  68637. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  68638. get: function () {
  68639. return this._maxPoint;
  68640. },
  68641. enumerable: true,
  68642. configurable: true
  68643. });
  68644. // Methods
  68645. OctreeBlock.prototype.addEntry = function (entry) {
  68646. if (this.blocks) {
  68647. for (var index = 0; index < this.blocks.length; index++) {
  68648. var block = this.blocks[index];
  68649. block.addEntry(entry);
  68650. }
  68651. return;
  68652. }
  68653. this._creationFunc(entry, this);
  68654. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  68655. this.createInnerBlocks();
  68656. }
  68657. };
  68658. OctreeBlock.prototype.addEntries = function (entries) {
  68659. for (var index = 0; index < entries.length; index++) {
  68660. var mesh = entries[index];
  68661. this.addEntry(mesh);
  68662. }
  68663. };
  68664. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  68665. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  68666. if (this.blocks) {
  68667. for (var index = 0; index < this.blocks.length; index++) {
  68668. var block = this.blocks[index];
  68669. block.select(frustumPlanes, selection, allowDuplicate);
  68670. }
  68671. return;
  68672. }
  68673. if (allowDuplicate) {
  68674. selection.concat(this.entries);
  68675. }
  68676. else {
  68677. selection.concatWithNoDuplicate(this.entries);
  68678. }
  68679. }
  68680. };
  68681. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  68682. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  68683. if (this.blocks) {
  68684. for (var index = 0; index < this.blocks.length; index++) {
  68685. var block = this.blocks[index];
  68686. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  68687. }
  68688. return;
  68689. }
  68690. if (allowDuplicate) {
  68691. selection.concat(this.entries);
  68692. }
  68693. else {
  68694. selection.concatWithNoDuplicate(this.entries);
  68695. }
  68696. }
  68697. };
  68698. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  68699. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  68700. if (this.blocks) {
  68701. for (var index = 0; index < this.blocks.length; index++) {
  68702. var block = this.blocks[index];
  68703. block.intersectsRay(ray, selection);
  68704. }
  68705. return;
  68706. }
  68707. selection.concatWithNoDuplicate(this.entries);
  68708. }
  68709. };
  68710. OctreeBlock.prototype.createInnerBlocks = function () {
  68711. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  68712. };
  68713. return OctreeBlock;
  68714. }());
  68715. BABYLON.OctreeBlock = OctreeBlock;
  68716. })(BABYLON || (BABYLON = {}));
  68717. //# sourceMappingURL=babylon.octreeBlock.js.map
  68718. var BABYLON;
  68719. (function (BABYLON) {
  68720. var SIMDVector3 = /** @class */ (function () {
  68721. function SIMDVector3() {
  68722. }
  68723. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  68724. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  68725. };
  68726. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  68727. var m = transformation.m;
  68728. var m0 = SIMD.Float32x4.load(m, 0);
  68729. var m1 = SIMD.Float32x4.load(m, 4);
  68730. var m2 = SIMD.Float32x4.load(m, 8);
  68731. var m3 = SIMD.Float32x4.load(m, 12);
  68732. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  68733. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  68734. result.x = SIMD.Float32x4.extractLane(r, 0);
  68735. result.y = SIMD.Float32x4.extractLane(r, 1);
  68736. result.z = SIMD.Float32x4.extractLane(r, 2);
  68737. };
  68738. return SIMDVector3;
  68739. }());
  68740. var SIMDMatrix = /** @class */ (function () {
  68741. function SIMDMatrix() {
  68742. }
  68743. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  68744. var tm = this.m;
  68745. var om = other.m;
  68746. var m0 = SIMD.Float32x4.load(om, 0);
  68747. var m1 = SIMD.Float32x4.load(om, 4);
  68748. var m2 = SIMD.Float32x4.load(om, 8);
  68749. var m3 = SIMD.Float32x4.load(om, 12);
  68750. for (var i = 0; i < 16; i += 4) {
  68751. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  68752. }
  68753. return this;
  68754. };
  68755. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  68756. var src = this.m;
  68757. var dest = other.m;
  68758. // Load the 4 rows
  68759. var src0 = SIMD.Float32x4.load(src, 0);
  68760. var src1 = SIMD.Float32x4.load(src, 4);
  68761. var src2 = SIMD.Float32x4.load(src, 8);
  68762. var src3 = SIMD.Float32x4.load(src, 12);
  68763. // Transpose the source matrix. Sort of. Not a true transpose operation
  68764. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  68765. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  68766. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  68767. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  68768. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  68769. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  68770. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  68771. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  68772. // This is a true transposition, but it will lead to an incorrect result
  68773. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  68774. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  68775. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68776. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68777. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  68778. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  68779. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68780. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68781. // ----
  68782. tmp1 = SIMD.Float32x4.mul(row2, row3);
  68783. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68784. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  68785. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  68786. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68787. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  68788. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  68789. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  68790. // ----
  68791. tmp1 = SIMD.Float32x4.mul(row1, row2);
  68792. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68793. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  68794. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  68795. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68796. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  68797. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  68798. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  68799. // ----
  68800. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  68801. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68802. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  68803. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  68804. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  68805. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68806. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  68807. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  68808. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  68809. // ----
  68810. tmp1 = SIMD.Float32x4.mul(row0, row1);
  68811. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68812. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68813. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  68814. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68815. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68816. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  68817. // ----
  68818. tmp1 = SIMD.Float32x4.mul(row0, row3);
  68819. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68820. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  68821. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  68822. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68823. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  68824. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  68825. // ----
  68826. tmp1 = SIMD.Float32x4.mul(row0, row2);
  68827. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68828. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  68829. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  68830. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68831. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  68832. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  68833. // Compute determinant
  68834. var det = SIMD.Float32x4.mul(row0, minor0);
  68835. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  68836. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  68837. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  68838. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  68839. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  68840. // These shuffles aren't necessary if the faulty transposition is done
  68841. // up at the top of this function.
  68842. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  68843. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  68844. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  68845. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  68846. // Compute final values by multiplying with 1/det
  68847. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  68848. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  68849. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  68850. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  68851. return this;
  68852. };
  68853. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  68854. var out = result.m;
  68855. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  68856. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  68857. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  68858. // cc.kmVec3Subtract(f, pCenter, pEye);
  68859. var f = SIMD.Float32x4.sub(center, eye);
  68860. // cc.kmVec3Normalize(f, f);
  68861. var tmp = SIMD.Float32x4.mul(f, f);
  68862. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68863. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68864. // cc.kmVec3Assign(up, pUp);
  68865. // cc.kmVec3Normalize(up, up);
  68866. tmp = SIMD.Float32x4.mul(up, up);
  68867. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68868. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68869. // cc.kmVec3Cross(s, f, up);
  68870. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  68871. // cc.kmVec3Normalize(s, s);
  68872. tmp = SIMD.Float32x4.mul(s, s);
  68873. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68874. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68875. // cc.kmVec3Cross(u, s, f);
  68876. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  68877. // cc.kmVec3Normalize(s, s);
  68878. tmp = SIMD.Float32x4.mul(s, s);
  68879. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68880. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68881. var zero = SIMD.Float32x4.splat(0.0);
  68882. s = SIMD.Float32x4.neg(s);
  68883. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  68884. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  68885. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  68886. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  68887. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  68888. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  68889. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  68890. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68891. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  68892. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68893. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  68894. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68895. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  68896. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68897. };
  68898. return SIMDMatrix;
  68899. }());
  68900. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  68901. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  68902. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  68903. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  68904. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  68905. var SIMDHelper = /** @class */ (function () {
  68906. function SIMDHelper() {
  68907. }
  68908. Object.defineProperty(SIMDHelper, "IsEnabled", {
  68909. get: function () {
  68910. return SIMDHelper._isEnabled;
  68911. },
  68912. enumerable: true,
  68913. configurable: true
  68914. });
  68915. SIMDHelper.DisableSIMD = function () {
  68916. // Replace functions
  68917. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  68918. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  68919. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  68920. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  68921. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  68922. SIMDHelper._isEnabled = false;
  68923. };
  68924. SIMDHelper.EnableSIMD = function () {
  68925. if (self.SIMD === undefined) {
  68926. return;
  68927. }
  68928. // check if polyfills needed
  68929. if (!self.Math.fround) {
  68930. self.Math.fround = (function (array) { return function (x) {
  68931. return array[0] = x, array[0];
  68932. }; })(new Float32Array(1));
  68933. }
  68934. if (!self.Math.imul) {
  68935. self.Math.imul = function (a, b) {
  68936. var ah = (a >>> 16) & 0xffff;
  68937. var al = a & 0xffff;
  68938. var bh = (b >>> 16) & 0xffff;
  68939. var bl = b & 0xffff;
  68940. // the shift by 0 fixes the sign on the high part
  68941. // the final |0 converts the unsigned value into a signed value
  68942. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  68943. };
  68944. }
  68945. // Replace functions
  68946. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  68947. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  68948. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  68949. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  68950. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  68951. SIMDHelper._isEnabled = true;
  68952. };
  68953. SIMDHelper._isEnabled = false;
  68954. return SIMDHelper;
  68955. }());
  68956. BABYLON.SIMDHelper = SIMDHelper;
  68957. })(BABYLON || (BABYLON = {}));
  68958. //# sourceMappingURL=babylon.math.SIMD.js.map
  68959. var BABYLON;
  68960. (function (BABYLON) {
  68961. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  68962. __extends(VRDistortionCorrectionPostProcess, _super);
  68963. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  68964. var _this = _super.call(this, name, "vrDistortionCorrection", [
  68965. 'LensCenter',
  68966. 'Scale',
  68967. 'ScaleIn',
  68968. 'HmdWarpParam'
  68969. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  68970. _this._isRightEye = isRightEye;
  68971. _this._distortionFactors = vrMetrics.distortionK;
  68972. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  68973. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  68974. _this.adaptScaleToCurrentViewport = true;
  68975. _this.onSizeChangedObservable.add(function () {
  68976. _this.aspectRatio = _this.width * .5 / _this.height;
  68977. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  68978. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  68979. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  68980. });
  68981. _this.onApplyObservable.add(function (effect) {
  68982. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  68983. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  68984. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  68985. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  68986. });
  68987. return _this;
  68988. }
  68989. return VRDistortionCorrectionPostProcess;
  68990. }(BABYLON.PostProcess));
  68991. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  68992. })(BABYLON || (BABYLON = {}));
  68993. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  68994. var BABYLON;
  68995. (function (BABYLON) {
  68996. var AnaglyphPostProcess = /** @class */ (function (_super) {
  68997. __extends(AnaglyphPostProcess, _super);
  68998. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  68999. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  69000. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69001. _this.onApplyObservable.add(function (effect) {
  69002. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  69003. });
  69004. return _this;
  69005. }
  69006. return AnaglyphPostProcess;
  69007. }(BABYLON.PostProcess));
  69008. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  69009. })(BABYLON || (BABYLON = {}));
  69010. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  69011. var BABYLON;
  69012. (function (BABYLON) {
  69013. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  69014. __extends(StereoscopicInterlacePostProcess, _super);
  69015. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  69016. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  69017. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69018. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69019. _this.onSizeChangedObservable.add(function () {
  69020. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69021. });
  69022. _this.onApplyObservable.add(function (effect) {
  69023. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  69024. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  69025. });
  69026. return _this;
  69027. }
  69028. return StereoscopicInterlacePostProcess;
  69029. }(BABYLON.PostProcess));
  69030. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  69031. })(BABYLON || (BABYLON = {}));
  69032. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  69033. var BABYLON;
  69034. (function (BABYLON) {
  69035. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  69036. function FreeCameraDeviceOrientationInput() {
  69037. var _this = this;
  69038. this._screenOrientationAngle = 0;
  69039. this._screenQuaternion = new BABYLON.Quaternion();
  69040. this._alpha = 0;
  69041. this._beta = 0;
  69042. this._gamma = 0;
  69043. this._orientationChanged = function () {
  69044. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  69045. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  69046. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  69047. };
  69048. this._deviceOrientation = function (evt) {
  69049. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  69050. _this._beta = evt.beta !== null ? evt.beta : 0;
  69051. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  69052. };
  69053. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  69054. this._orientationChanged();
  69055. }
  69056. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  69057. get: function () {
  69058. return this._camera;
  69059. },
  69060. set: function (camera) {
  69061. this._camera = camera;
  69062. if (this._camera != null && !this._camera.rotationQuaternion) {
  69063. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  69064. }
  69065. },
  69066. enumerable: true,
  69067. configurable: true
  69068. });
  69069. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69070. window.addEventListener("orientationchange", this._orientationChanged);
  69071. window.addEventListener("deviceorientation", this._deviceOrientation);
  69072. //In certain cases, the attach control is called AFTER orientation was changed,
  69073. //So this is needed.
  69074. this._orientationChanged();
  69075. };
  69076. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  69077. window.removeEventListener("orientationchange", this._orientationChanged);
  69078. window.removeEventListener("deviceorientation", this._deviceOrientation);
  69079. };
  69080. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  69081. //if no device orientation provided, don't update the rotation.
  69082. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  69083. if (!this._alpha)
  69084. return;
  69085. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  69086. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  69087. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  69088. //Mirror on XY Plane
  69089. this._camera.rotationQuaternion.z *= -1;
  69090. this._camera.rotationQuaternion.w *= -1;
  69091. };
  69092. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  69093. return "FreeCameraDeviceOrientationInput";
  69094. };
  69095. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  69096. return "deviceOrientation";
  69097. };
  69098. return FreeCameraDeviceOrientationInput;
  69099. }());
  69100. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  69101. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  69102. })(BABYLON || (BABYLON = {}));
  69103. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  69104. var BABYLON;
  69105. (function (BABYLON) {
  69106. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  69107. function ArcRotateCameraVRDeviceOrientationInput() {
  69108. this.alphaCorrection = 1;
  69109. this.betaCorrection = 1;
  69110. this.gammaCorrection = 1;
  69111. this._alpha = 0;
  69112. this._beta = 0;
  69113. this._gamma = 0;
  69114. this._dirty = false;
  69115. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  69116. }
  69117. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69118. this.camera.attachControl(element, noPreventDefault);
  69119. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  69120. };
  69121. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  69122. if (evt.alpha !== null) {
  69123. this._alpha = +evt.alpha | 0;
  69124. }
  69125. if (evt.beta !== null) {
  69126. this._beta = +evt.beta | 0;
  69127. }
  69128. if (evt.gamma !== null) {
  69129. this._gamma = +evt.gamma | 0;
  69130. }
  69131. this._dirty = true;
  69132. };
  69133. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  69134. if (this._dirty) {
  69135. this._dirty = false;
  69136. if (this._gamma < 0) {
  69137. this._gamma = 180 + this._gamma;
  69138. }
  69139. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  69140. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  69141. }
  69142. };
  69143. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  69144. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  69145. };
  69146. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  69147. return "ArcRotateCameraVRDeviceOrientationInput";
  69148. };
  69149. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  69150. return "VRDeviceOrientation";
  69151. };
  69152. return ArcRotateCameraVRDeviceOrientationInput;
  69153. }());
  69154. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  69155. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  69156. })(BABYLON || (BABYLON = {}));
  69157. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  69158. var BABYLON;
  69159. (function (BABYLON) {
  69160. var VRCameraMetrics = /** @class */ (function () {
  69161. function VRCameraMetrics() {
  69162. this.compensateDistortion = true;
  69163. }
  69164. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  69165. get: function () {
  69166. return this.hResolution / (2 * this.vResolution);
  69167. },
  69168. enumerable: true,
  69169. configurable: true
  69170. });
  69171. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  69172. get: function () {
  69173. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  69174. },
  69175. enumerable: true,
  69176. configurable: true
  69177. });
  69178. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  69179. get: function () {
  69180. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69181. var h = (4 * meters) / this.hScreenSize;
  69182. return BABYLON.Matrix.Translation(h, 0, 0);
  69183. },
  69184. enumerable: true,
  69185. configurable: true
  69186. });
  69187. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  69188. get: function () {
  69189. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69190. var h = (4 * meters) / this.hScreenSize;
  69191. return BABYLON.Matrix.Translation(-h, 0, 0);
  69192. },
  69193. enumerable: true,
  69194. configurable: true
  69195. });
  69196. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  69197. get: function () {
  69198. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  69199. },
  69200. enumerable: true,
  69201. configurable: true
  69202. });
  69203. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  69204. get: function () {
  69205. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  69206. },
  69207. enumerable: true,
  69208. configurable: true
  69209. });
  69210. VRCameraMetrics.GetDefault = function () {
  69211. var result = new VRCameraMetrics();
  69212. result.hResolution = 1280;
  69213. result.vResolution = 800;
  69214. result.hScreenSize = 0.149759993;
  69215. result.vScreenSize = 0.0935999975;
  69216. result.vScreenCenter = 0.0467999987;
  69217. result.eyeToScreenDistance = 0.0410000011;
  69218. result.lensSeparationDistance = 0.0635000020;
  69219. result.interpupillaryDistance = 0.0640000030;
  69220. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  69221. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  69222. result.postProcessScaleFactor = 1.714605507808412;
  69223. result.lensCenterOffset = 0.151976421;
  69224. return result;
  69225. };
  69226. return VRCameraMetrics;
  69227. }());
  69228. BABYLON.VRCameraMetrics = VRCameraMetrics;
  69229. })(BABYLON || (BABYLON = {}));
  69230. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  69231. var BABYLON;
  69232. (function (BABYLON) {
  69233. var WebVRFreeCamera = /** @class */ (function (_super) {
  69234. __extends(WebVRFreeCamera, _super);
  69235. function WebVRFreeCamera(name, position, scene, webVROptions) {
  69236. if (webVROptions === void 0) { webVROptions = {}; }
  69237. var _this = _super.call(this, name, position, scene) || this;
  69238. _this.webVROptions = webVROptions;
  69239. _this._vrDevice = null;
  69240. _this.rawPose = null;
  69241. _this._specsVersion = "1.1";
  69242. _this._attached = false;
  69243. _this._descendants = [];
  69244. _this.devicePosition = BABYLON.Vector3.Zero();
  69245. _this.deviceScaleFactor = 1;
  69246. _this.controllers = [];
  69247. _this.onControllersAttachedObservable = new BABYLON.Observable();
  69248. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  69249. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  69250. _this.minZ = 0.1;
  69251. //legacy support - the compensation boolean was removed.
  69252. if (arguments.length === 5) {
  69253. _this.webVROptions = arguments[4];
  69254. }
  69255. // default webVR options
  69256. if (_this.webVROptions.trackPosition == undefined) {
  69257. _this.webVROptions.trackPosition = true;
  69258. }
  69259. if (_this.webVROptions.controllerMeshes == undefined) {
  69260. _this.webVROptions.controllerMeshes = true;
  69261. }
  69262. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  69263. _this.webVROptions.defaultLightingOnControllers = true;
  69264. }
  69265. _this.rotationQuaternion = new BABYLON.Quaternion();
  69266. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69267. if (_this.webVROptions && _this.webVROptions.positionScale) {
  69268. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  69269. }
  69270. //enable VR
  69271. var engine = _this.getEngine();
  69272. _this._onVREnabled = function (success) { if (success) {
  69273. _this.initControllers();
  69274. } };
  69275. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  69276. engine.initWebVR().add(function (event) {
  69277. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  69278. return;
  69279. }
  69280. _this._vrDevice = event.vrDisplay;
  69281. //reset the rig parameters.
  69282. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  69283. if (_this._attached) {
  69284. _this.getEngine().enableVR();
  69285. }
  69286. });
  69287. if (typeof (VRFrameData) !== "undefined")
  69288. _this._frameData = new VRFrameData();
  69289. /**
  69290. * The idea behind the following lines:
  69291. * objects that have the camera as parent should actually have the rig cameras as a parent.
  69292. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  69293. * the second will not show it correctly.
  69294. *
  69295. * To solve this - each object that has the camera as parent will be added to a protected array.
  69296. * When the rig camera renders, it will take this array and set all of those to be its children.
  69297. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  69298. * Amazing!
  69299. */
  69300. scene.onBeforeCameraRenderObservable.add(function (camera) {
  69301. if (camera.parent === _this && _this.rigParenting) {
  69302. _this._descendants = _this.getDescendants(true, function (n) {
  69303. // don't take the cameras or the controllers!
  69304. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  69305. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  69306. return !isController && !isRigCamera;
  69307. });
  69308. _this._descendants.forEach(function (node) {
  69309. node.parent = camera;
  69310. });
  69311. }
  69312. });
  69313. scene.onAfterCameraRenderObservable.add(function (camera) {
  69314. if (camera.parent === _this && _this.rigParenting) {
  69315. _this._descendants.forEach(function (node) {
  69316. node.parent = _this;
  69317. });
  69318. }
  69319. });
  69320. return _this;
  69321. }
  69322. WebVRFreeCamera.prototype.dispose = function () {
  69323. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  69324. _super.prototype.dispose.call(this);
  69325. };
  69326. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  69327. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  69328. var gp = _a[_i];
  69329. if (gp.hand === name) {
  69330. return gp;
  69331. }
  69332. }
  69333. return null;
  69334. };
  69335. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  69336. get: function () {
  69337. if (!this._leftController) {
  69338. this._leftController = this.getControllerByName("left");
  69339. }
  69340. return this._leftController;
  69341. },
  69342. enumerable: true,
  69343. configurable: true
  69344. });
  69345. ;
  69346. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  69347. get: function () {
  69348. if (!this._rightController) {
  69349. this._rightController = this.getControllerByName("right");
  69350. }
  69351. return this._rightController;
  69352. },
  69353. enumerable: true,
  69354. configurable: true
  69355. });
  69356. ;
  69357. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  69358. if (length === void 0) { length = 100; }
  69359. if (this.leftCamera) {
  69360. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  69361. }
  69362. else {
  69363. return _super.prototype.getForwardRay.call(this, length);
  69364. }
  69365. };
  69366. WebVRFreeCamera.prototype._checkInputs = function () {
  69367. if (this._vrDevice && this._vrDevice.isPresenting) {
  69368. this._vrDevice.getFrameData(this._frameData);
  69369. this.updateFromDevice(this._frameData.pose);
  69370. }
  69371. _super.prototype._checkInputs.call(this);
  69372. };
  69373. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  69374. if (poseData && poseData.orientation) {
  69375. this.rawPose = poseData;
  69376. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  69377. if (this.getScene().useRightHandedSystem) {
  69378. this.deviceRotationQuaternion.z *= -1;
  69379. this.deviceRotationQuaternion.w *= -1;
  69380. }
  69381. if (this.webVROptions.trackPosition && this.rawPose.position) {
  69382. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  69383. if (this.getScene().useRightHandedSystem) {
  69384. this.devicePosition.z *= -1;
  69385. }
  69386. }
  69387. }
  69388. };
  69389. /**
  69390. * WebVR's attach control will start broadcasting frames to the device.
  69391. * Note that in certain browsers (chrome for example) this function must be called
  69392. * within a user-interaction callback. Example:
  69393. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  69394. *
  69395. * @param {HTMLElement} element
  69396. * @param {boolean} [noPreventDefault]
  69397. *
  69398. * @memberOf WebVRFreeCamera
  69399. */
  69400. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  69401. _super.prototype.attachControl.call(this, element, noPreventDefault);
  69402. this._attached = true;
  69403. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  69404. if (this._vrDevice) {
  69405. this.getEngine().enableVR();
  69406. }
  69407. };
  69408. WebVRFreeCamera.prototype.detachControl = function (element) {
  69409. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69410. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69411. _super.prototype.detachControl.call(this, element);
  69412. this._attached = false;
  69413. this.getEngine().disableVR();
  69414. };
  69415. WebVRFreeCamera.prototype.getClassName = function () {
  69416. return "WebVRFreeCamera";
  69417. };
  69418. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  69419. //uses the vrDisplay's "resetPose()".
  69420. //pitch and roll won't be affected.
  69421. this._vrDevice.resetPose();
  69422. };
  69423. WebVRFreeCamera.prototype._updateRigCameras = function () {
  69424. var camLeft = this._rigCameras[0];
  69425. var camRight = this._rigCameras[1];
  69426. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69427. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69428. camLeft.position.copyFrom(this.devicePosition);
  69429. camRight.position.copyFrom(this.devicePosition);
  69430. };
  69431. /**
  69432. * This function is called by the two RIG cameras.
  69433. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  69434. */
  69435. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  69436. var _this = this;
  69437. //WebVR 1.1
  69438. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  69439. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  69440. if (!this.getScene().useRightHandedSystem) {
  69441. [2, 6, 8, 9, 14].forEach(function (num) {
  69442. _this._webvrViewMatrix.m[num] *= -1;
  69443. });
  69444. }
  69445. // update the camera rotation matrix
  69446. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  69447. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  69448. // Computing target and final matrix
  69449. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  69450. var parentCamera = this._cameraRigParams["parentCamera"];
  69451. // should the view matrix be updated with scale and position offset?
  69452. if (parentCamera.deviceScaleFactor !== 1) {
  69453. this._webvrViewMatrix.invert();
  69454. // scale the position, if set
  69455. if (parentCamera.deviceScaleFactor) {
  69456. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  69457. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  69458. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  69459. }
  69460. this._webvrViewMatrix.invert();
  69461. }
  69462. return this._webvrViewMatrix;
  69463. };
  69464. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  69465. var _this = this;
  69466. var parentCamera = this.parent;
  69467. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  69468. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  69469. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  69470. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  69471. //babylon compatible matrix
  69472. if (!this.getScene().useRightHandedSystem) {
  69473. [8, 9, 10, 11].forEach(function (num) {
  69474. _this._projectionMatrix.m[num] *= -1;
  69475. });
  69476. }
  69477. return this._projectionMatrix;
  69478. };
  69479. WebVRFreeCamera.prototype.initControllers = function () {
  69480. var _this = this;
  69481. this.controllers = [];
  69482. var manager = this.getScene().gamepadManager;
  69483. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69484. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69485. var webVrController = gamepad;
  69486. if (webVrController.defaultModel) {
  69487. webVrController.defaultModel.setEnabled(false);
  69488. }
  69489. }
  69490. });
  69491. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69492. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69493. var webVrController_1 = gamepad;
  69494. if (_this.webVROptions.controllerMeshes) {
  69495. if (webVrController_1.defaultModel) {
  69496. webVrController_1.defaultModel.setEnabled(true);
  69497. }
  69498. else {
  69499. // Load the meshes
  69500. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  69501. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  69502. if (_this.webVROptions.defaultLightingOnControllers) {
  69503. if (!_this._lightOnControllers) {
  69504. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  69505. }
  69506. var activateLightOnSubMeshes_1 = function (mesh, light) {
  69507. var children = mesh.getChildren();
  69508. if (children.length !== 0) {
  69509. children.forEach(function (mesh) {
  69510. light.includedOnlyMeshes.push(mesh);
  69511. activateLightOnSubMeshes_1(mesh, light);
  69512. });
  69513. }
  69514. };
  69515. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  69516. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  69517. }
  69518. });
  69519. }
  69520. }
  69521. webVrController_1.attachToPoseControlledCamera(_this);
  69522. // since this is async - sanity check. Is the controller already stored?
  69523. if (_this.controllers.indexOf(webVrController_1) === -1) {
  69524. //add to the controllers array
  69525. _this.controllers.push(webVrController_1);
  69526. //did we find enough controllers? Great! let the developer know.
  69527. if (_this.controllers.length >= 2) {
  69528. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  69529. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  69530. // So we're overriding setting left & right manually to be sure
  69531. var firstViveWandDetected = false;
  69532. for (var i = 0; i < _this.controllers.length; i++) {
  69533. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  69534. if (!firstViveWandDetected) {
  69535. firstViveWandDetected = true;
  69536. _this.controllers[i].hand = "left";
  69537. }
  69538. else {
  69539. _this.controllers[i].hand = "right";
  69540. }
  69541. }
  69542. }
  69543. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  69544. }
  69545. }
  69546. }
  69547. });
  69548. };
  69549. return WebVRFreeCamera;
  69550. }(BABYLON.FreeCamera));
  69551. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  69552. })(BABYLON || (BABYLON = {}));
  69553. //# sourceMappingURL=babylon.webVRCamera.js.map
  69554. var BABYLON;
  69555. (function (BABYLON) {
  69556. // We're mainly based on the logic defined into the FreeCamera code
  69557. var DeviceOrientationCamera = /** @class */ (function (_super) {
  69558. __extends(DeviceOrientationCamera, _super);
  69559. function DeviceOrientationCamera(name, position, scene) {
  69560. var _this = _super.call(this, name, position, scene) || this;
  69561. _this._quaternionCache = new BABYLON.Quaternion();
  69562. _this.inputs.addDeviceOrientation();
  69563. return _this;
  69564. }
  69565. DeviceOrientationCamera.prototype.getClassName = function () {
  69566. return "DeviceOrientationCamera";
  69567. };
  69568. DeviceOrientationCamera.prototype._checkInputs = function () {
  69569. _super.prototype._checkInputs.call(this);
  69570. this._quaternionCache.copyFrom(this.rotationQuaternion);
  69571. if (this._initialQuaternion) {
  69572. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69573. }
  69574. };
  69575. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  69576. var _this = this;
  69577. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  69578. //can only work if this camera has a rotation quaternion already.
  69579. if (!this.rotationQuaternion)
  69580. return;
  69581. if (!this._initialQuaternion) {
  69582. this._initialQuaternion = new BABYLON.Quaternion();
  69583. }
  69584. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  69585. ['x', 'y', 'z'].forEach(function (axisName) {
  69586. if (!axis[axisName]) {
  69587. _this._initialQuaternion[axisName] = 0;
  69588. }
  69589. else {
  69590. _this._initialQuaternion[axisName] *= -1;
  69591. }
  69592. });
  69593. this._initialQuaternion.normalize();
  69594. //force rotation update
  69595. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69596. };
  69597. return DeviceOrientationCamera;
  69598. }(BABYLON.FreeCamera));
  69599. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  69600. })(BABYLON || (BABYLON = {}));
  69601. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  69602. var BABYLON;
  69603. (function (BABYLON) {
  69604. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  69605. __extends(VRDeviceOrientationFreeCamera, _super);
  69606. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69607. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69608. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69609. var _this = _super.call(this, name, position, scene) || this;
  69610. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69611. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69612. return _this;
  69613. }
  69614. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  69615. return "VRDeviceOrientationFreeCamera";
  69616. };
  69617. return VRDeviceOrientationFreeCamera;
  69618. }(BABYLON.DeviceOrientationCamera));
  69619. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  69620. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  69621. __extends(VRDeviceOrientationGamepadCamera, _super);
  69622. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69623. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69624. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69625. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  69626. _this.inputs.addGamepad();
  69627. return _this;
  69628. }
  69629. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  69630. return "VRDeviceOrientationGamepadCamera";
  69631. };
  69632. return VRDeviceOrientationGamepadCamera;
  69633. }(VRDeviceOrientationFreeCamera));
  69634. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  69635. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  69636. __extends(VRDeviceOrientationArcRotateCamera, _super);
  69637. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  69638. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69639. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69640. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69641. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69642. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69643. _this.inputs.addVRDeviceOrientation();
  69644. return _this;
  69645. }
  69646. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  69647. return "VRDeviceOrientationArcRotateCamera";
  69648. };
  69649. return VRDeviceOrientationArcRotateCamera;
  69650. }(BABYLON.ArcRotateCamera));
  69651. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  69652. })(BABYLON || (BABYLON = {}));
  69653. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  69654. var BABYLON;
  69655. (function (BABYLON) {
  69656. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  69657. __extends(AnaglyphFreeCamera, _super);
  69658. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  69659. var _this = _super.call(this, name, position, scene) || this;
  69660. _this.interaxialDistance = interaxialDistance;
  69661. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69662. return _this;
  69663. }
  69664. AnaglyphFreeCamera.prototype.getClassName = function () {
  69665. return "AnaglyphFreeCamera";
  69666. };
  69667. return AnaglyphFreeCamera;
  69668. }(BABYLON.FreeCamera));
  69669. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  69670. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  69671. __extends(AnaglyphArcRotateCamera, _super);
  69672. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  69673. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69674. _this.interaxialDistance = interaxialDistance;
  69675. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69676. return _this;
  69677. }
  69678. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  69679. return "AnaglyphArcRotateCamera";
  69680. };
  69681. return AnaglyphArcRotateCamera;
  69682. }(BABYLON.ArcRotateCamera));
  69683. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  69684. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  69685. __extends(AnaglyphGamepadCamera, _super);
  69686. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  69687. var _this = _super.call(this, name, position, scene) || this;
  69688. _this.interaxialDistance = interaxialDistance;
  69689. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69690. return _this;
  69691. }
  69692. AnaglyphGamepadCamera.prototype.getClassName = function () {
  69693. return "AnaglyphGamepadCamera";
  69694. };
  69695. return AnaglyphGamepadCamera;
  69696. }(BABYLON.GamepadCamera));
  69697. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  69698. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  69699. __extends(AnaglyphUniversalCamera, _super);
  69700. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  69701. var _this = _super.call(this, name, position, scene) || this;
  69702. _this.interaxialDistance = interaxialDistance;
  69703. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69704. return _this;
  69705. }
  69706. AnaglyphUniversalCamera.prototype.getClassName = function () {
  69707. return "AnaglyphUniversalCamera";
  69708. };
  69709. return AnaglyphUniversalCamera;
  69710. }(BABYLON.UniversalCamera));
  69711. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  69712. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  69713. __extends(StereoscopicFreeCamera, _super);
  69714. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69715. var _this = _super.call(this, name, position, scene) || this;
  69716. _this.interaxialDistance = interaxialDistance;
  69717. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69718. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69719. return _this;
  69720. }
  69721. StereoscopicFreeCamera.prototype.getClassName = function () {
  69722. return "StereoscopicFreeCamera";
  69723. };
  69724. return StereoscopicFreeCamera;
  69725. }(BABYLON.FreeCamera));
  69726. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  69727. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  69728. __extends(StereoscopicArcRotateCamera, _super);
  69729. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  69730. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69731. _this.interaxialDistance = interaxialDistance;
  69732. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69733. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69734. return _this;
  69735. }
  69736. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  69737. return "StereoscopicArcRotateCamera";
  69738. };
  69739. return StereoscopicArcRotateCamera;
  69740. }(BABYLON.ArcRotateCamera));
  69741. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  69742. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  69743. __extends(StereoscopicGamepadCamera, _super);
  69744. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69745. var _this = _super.call(this, name, position, scene) || this;
  69746. _this.interaxialDistance = interaxialDistance;
  69747. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69748. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69749. return _this;
  69750. }
  69751. StereoscopicGamepadCamera.prototype.getClassName = function () {
  69752. return "StereoscopicGamepadCamera";
  69753. };
  69754. return StereoscopicGamepadCamera;
  69755. }(BABYLON.GamepadCamera));
  69756. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  69757. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  69758. __extends(StereoscopicUniversalCamera, _super);
  69759. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69760. var _this = _super.call(this, name, position, scene) || this;
  69761. _this.interaxialDistance = interaxialDistance;
  69762. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69763. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69764. return _this;
  69765. }
  69766. StereoscopicUniversalCamera.prototype.getClassName = function () {
  69767. return "StereoscopicUniversalCamera";
  69768. };
  69769. return StereoscopicUniversalCamera;
  69770. }(BABYLON.UniversalCamera));
  69771. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  69772. })(BABYLON || (BABYLON = {}));
  69773. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  69774. var BABYLON;
  69775. (function (BABYLON) {
  69776. var VRExperienceHelper = /** @class */ (function () {
  69777. function VRExperienceHelper(scene, webVROptions) {
  69778. if (webVROptions === void 0) { webVROptions = {}; }
  69779. var _this = this;
  69780. this.webVROptions = webVROptions;
  69781. // Can the system support WebVR, even if a headset isn't plugged in?
  69782. this._webVRsupported = false;
  69783. // If WebVR is supported, is a headset plugged in and are we ready to present?
  69784. this._webVRready = false;
  69785. // Are we waiting for the requestPresent callback to complete?
  69786. this._webVRrequesting = false;
  69787. // Are we presenting to the headset right now?
  69788. this._webVRpresenting = false;
  69789. // Are we presenting in the fullscreen fallback?
  69790. this._fullscreenVRpresenting = false;
  69791. this._scene = scene;
  69792. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  69793. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  69794. }
  69795. else {
  69796. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  69797. if (scene.activeCamera.rotation) {
  69798. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  69799. }
  69800. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  69801. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  69802. }
  69803. this._scene.activeCamera = this._deviceOrientationCamera;
  69804. this._position = this._scene.activeCamera.position;
  69805. this._canvas = scene.getEngine().getRenderingCanvas();
  69806. if (this._canvas) {
  69807. this._scene.activeCamera.attachControl(this._canvas);
  69808. }
  69809. this._btnVR = document.createElement("BUTTON");
  69810. this._btnVR.className = "babylonVRicon";
  69811. this._btnVR.id = "babylonVRiconbtn";
  69812. this._btnVR.title = "Click to switch to VR";
  69813. 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) }";
  69814. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  69815. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  69816. // css += ".babylonVRicon.vrdisplaysupported { }";
  69817. // css += ".babylonVRicon.vrdisplayready { }";
  69818. // css += ".babylonVRicon.vrdisplayrequesting { }";
  69819. var style = document.createElement('style');
  69820. style.appendChild(document.createTextNode(css));
  69821. document.getElementsByTagName('head')[0].appendChild(style);
  69822. if (this._canvas) {
  69823. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69824. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69825. this._btnVR.addEventListener("click", function () {
  69826. _this.enterVR();
  69827. });
  69828. window.addEventListener("resize", function () {
  69829. if (_this._canvas) {
  69830. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  69831. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  69832. }
  69833. if (_this._fullscreenVRpresenting && _this._webVRready) {
  69834. _this.exitVR();
  69835. }
  69836. });
  69837. }
  69838. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69839. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69840. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69841. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69842. document.body.appendChild(this._btnVR);
  69843. // Exiting VR mode using 'ESC' key on desktop
  69844. this._onKeyDown = function (event) {
  69845. if (event.keyCode === 27 && _this.isInVRMode()) {
  69846. _this.exitVR();
  69847. }
  69848. };
  69849. document.addEventListener("keydown", this._onKeyDown);
  69850. // Exiting VR mode double tapping the touch screen
  69851. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  69852. if (_this.isInVRMode()) {
  69853. _this.exitVR();
  69854. if (_this._fullscreenVRpresenting) {
  69855. _this._scene.getEngine().switchFullscreen(true);
  69856. }
  69857. }
  69858. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  69859. // Listen for WebVR display changes
  69860. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  69861. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  69862. this._onVRRequestPresentStart = function () {
  69863. _this._webVRrequesting = true;
  69864. _this.updateButtonVisibility();
  69865. };
  69866. this._onVRRequestPresentComplete = function (success) {
  69867. _this._webVRrequesting = false;
  69868. _this.updateButtonVisibility();
  69869. };
  69870. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  69871. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  69872. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  69873. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  69874. // Create the cameras
  69875. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  69876. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  69877. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  69878. this.updateButtonVisibility();
  69879. }
  69880. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  69881. if (this.onControllerMeshLoaded) {
  69882. this.onControllerMeshLoaded(webVRController);
  69883. }
  69884. };
  69885. VRExperienceHelper.prototype._onFullscreenChange = function () {
  69886. if (document.fullscreen !== undefined) {
  69887. this._fullscreenVRpresenting = document.fullscreen;
  69888. }
  69889. else if (document.mozFullScreen !== undefined) {
  69890. this._fullscreenVRpresenting = document.mozFullScreen;
  69891. }
  69892. else if (document.webkitIsFullScreen !== undefined) {
  69893. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  69894. }
  69895. else if (document.msIsFullScreen !== undefined) {
  69896. this._fullscreenVRpresenting = document.msIsFullScreen;
  69897. }
  69898. if (!this._fullscreenVRpresenting && this._canvas) {
  69899. this.exitVR();
  69900. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69901. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69902. }
  69903. };
  69904. VRExperienceHelper.prototype.isInVRMode = function () {
  69905. return this._webVRpresenting || this._fullscreenVRpresenting;
  69906. };
  69907. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  69908. var vrDisplay = this._scene.getEngine().getVRDevice();
  69909. if (vrDisplay) {
  69910. var wasPresenting = this._webVRpresenting;
  69911. // A VR display is connected
  69912. this._webVRpresenting = vrDisplay.isPresenting;
  69913. if (wasPresenting && !this._webVRpresenting)
  69914. this.exitVR();
  69915. }
  69916. else {
  69917. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  69918. }
  69919. this.updateButtonVisibility();
  69920. };
  69921. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  69922. this._webVRsupported = eventArgs.vrSupported;
  69923. this._webVRready = !!eventArgs.vrDisplay;
  69924. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  69925. this.updateButtonVisibility();
  69926. };
  69927. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  69928. if (!this._btnVR) {
  69929. return;
  69930. }
  69931. this._btnVR.className = "babylonVRicon";
  69932. if (this.isInVRMode()) {
  69933. this._btnVR.className += " vrdisplaypresenting";
  69934. }
  69935. else {
  69936. if (this._webVRready)
  69937. this._btnVR.className += " vrdisplayready";
  69938. if (this._webVRsupported)
  69939. this._btnVR.className += " vrdisplaysupported";
  69940. if (this._webVRrequesting)
  69941. this._btnVR.className += " vrdisplayrequesting";
  69942. }
  69943. };
  69944. /**
  69945. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  69946. * Otherwise, will use the fullscreen API.
  69947. */
  69948. VRExperienceHelper.prototype.enterVR = function () {
  69949. if (this.onEnteringVR) {
  69950. this.onEnteringVR();
  69951. }
  69952. if (this._webVRrequesting)
  69953. return;
  69954. // If WebVR is supported and a headset is connected
  69955. if (this._webVRready) {
  69956. if (!this._webVRpresenting) {
  69957. this._webVRCamera.position = this._position;
  69958. this._scene.activeCamera = this._webVRCamera;
  69959. }
  69960. }
  69961. else {
  69962. this._vrDeviceOrientationCamera.position = this._position;
  69963. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  69964. this._scene.getEngine().switchFullscreen(true);
  69965. this.updateButtonVisibility();
  69966. }
  69967. if (this._scene.activeCamera && this._canvas) {
  69968. this._scene.activeCamera.attachControl(this._canvas);
  69969. }
  69970. };
  69971. /**
  69972. * Attempt to exit VR, or fullscreen.
  69973. */
  69974. VRExperienceHelper.prototype.exitVR = function () {
  69975. if (this.onExitingVR) {
  69976. this.onExitingVR();
  69977. }
  69978. if (this._webVRpresenting) {
  69979. this._scene.getEngine().disableVR();
  69980. }
  69981. if (this._scene.activeCamera) {
  69982. this._position = this._scene.activeCamera.position;
  69983. }
  69984. this._deviceOrientationCamera.position = this._position;
  69985. this._scene.activeCamera = this._deviceOrientationCamera;
  69986. if (this._canvas) {
  69987. this._scene.activeCamera.attachControl(this._canvas);
  69988. }
  69989. this.updateButtonVisibility();
  69990. };
  69991. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  69992. get: function () {
  69993. return this._position;
  69994. },
  69995. set: function (value) {
  69996. this._position = value;
  69997. if (this._scene.activeCamera) {
  69998. this._scene.activeCamera.position = value;
  69999. }
  70000. },
  70001. enumerable: true,
  70002. configurable: true
  70003. });
  70004. VRExperienceHelper.prototype.dispose = function () {
  70005. if (this.isInVRMode()) {
  70006. this.exitVR();
  70007. }
  70008. this._deviceOrientationCamera.dispose();
  70009. if (this._webVRCamera) {
  70010. this._webVRCamera.dispose();
  70011. }
  70012. if (this._vrDeviceOrientationCamera) {
  70013. this._vrDeviceOrientationCamera.dispose();
  70014. }
  70015. document.body.removeChild(this._btnVR);
  70016. document.removeEventListener("keydown", this._onKeyDown);
  70017. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70018. };
  70019. VRExperienceHelper.prototype.getClassName = function () {
  70020. return "VRExperienceHelper";
  70021. };
  70022. return VRExperienceHelper;
  70023. }());
  70024. BABYLON.VRExperienceHelper = VRExperienceHelper;
  70025. })(BABYLON || (BABYLON = {}));
  70026. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  70027. // Mainly based on these 2 articles :
  70028. // 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
  70029. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  70030. var BABYLON;
  70031. (function (BABYLON) {
  70032. var JoystickAxis;
  70033. (function (JoystickAxis) {
  70034. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  70035. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  70036. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  70037. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  70038. var VirtualJoystick = /** @class */ (function () {
  70039. function VirtualJoystick(leftJoystick) {
  70040. var _this = this;
  70041. if (leftJoystick) {
  70042. this._leftJoystick = true;
  70043. }
  70044. else {
  70045. this._leftJoystick = false;
  70046. }
  70047. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  70048. VirtualJoystick._globalJoystickIndex++;
  70049. // By default left & right arrow keys are moving the X
  70050. // and up & down keys are moving the Y
  70051. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70052. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70053. this.reverseLeftRight = false;
  70054. this.reverseUpDown = false;
  70055. // collections of pointers
  70056. this._touches = new BABYLON.StringDictionary();
  70057. this.deltaPosition = BABYLON.Vector3.Zero();
  70058. this._joystickSensibility = 25;
  70059. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70060. this._rotationSpeed = 25;
  70061. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  70062. this._rotateOnAxisRelativeToMesh = false;
  70063. this._onResize = function (evt) {
  70064. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70065. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70066. if (VirtualJoystick.vjCanvas) {
  70067. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  70068. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  70069. }
  70070. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  70071. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  70072. };
  70073. // injecting a canvas element on top of the canvas 3D game
  70074. if (!VirtualJoystick.vjCanvas) {
  70075. window.addEventListener("resize", this._onResize, false);
  70076. VirtualJoystick.vjCanvas = document.createElement("canvas");
  70077. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70078. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70079. VirtualJoystick.vjCanvas.width = window.innerWidth;
  70080. VirtualJoystick.vjCanvas.height = window.innerHeight;
  70081. VirtualJoystick.vjCanvas.style.width = "100%";
  70082. VirtualJoystick.vjCanvas.style.height = "100%";
  70083. VirtualJoystick.vjCanvas.style.position = "absolute";
  70084. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  70085. VirtualJoystick.vjCanvas.style.top = "0px";
  70086. VirtualJoystick.vjCanvas.style.left = "0px";
  70087. VirtualJoystick.vjCanvas.style.zIndex = "5";
  70088. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  70089. // Support for jQuery PEP polyfill
  70090. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  70091. var context = VirtualJoystick.vjCanvas.getContext('2d');
  70092. if (!context) {
  70093. throw new Error("Unable to create canvas for virtual joystick");
  70094. }
  70095. VirtualJoystick.vjCanvasContext = context;
  70096. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  70097. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70098. document.body.appendChild(VirtualJoystick.vjCanvas);
  70099. }
  70100. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  70101. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  70102. this.pressed = false;
  70103. // default joystick color
  70104. this._joystickColor = "cyan";
  70105. this._joystickPointerID = -1;
  70106. // current joystick position
  70107. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  70108. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  70109. // origin joystick position
  70110. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  70111. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  70112. this._onPointerDownHandlerRef = function (evt) {
  70113. _this._onPointerDown(evt);
  70114. };
  70115. this._onPointerMoveHandlerRef = function (evt) {
  70116. _this._onPointerMove(evt);
  70117. };
  70118. this._onPointerOutHandlerRef = function (evt) {
  70119. _this._onPointerUp(evt);
  70120. };
  70121. this._onPointerUpHandlerRef = function (evt) {
  70122. _this._onPointerUp(evt);
  70123. };
  70124. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  70125. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  70126. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  70127. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  70128. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  70129. evt.preventDefault(); // Disables system menu
  70130. }, false);
  70131. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70132. }
  70133. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  70134. this._joystickSensibility = newJoystickSensibility;
  70135. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70136. };
  70137. VirtualJoystick.prototype._onPointerDown = function (e) {
  70138. var positionOnScreenCondition;
  70139. e.preventDefault();
  70140. if (this._leftJoystick === true) {
  70141. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  70142. }
  70143. else {
  70144. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  70145. }
  70146. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  70147. // First contact will be dedicated to the virtual joystick
  70148. this._joystickPointerID = e.pointerId;
  70149. this._joystickPointerStartPos.x = e.clientX;
  70150. this._joystickPointerStartPos.y = e.clientY;
  70151. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  70152. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  70153. this._deltaJoystickVector.x = 0;
  70154. this._deltaJoystickVector.y = 0;
  70155. this.pressed = true;
  70156. this._touches.add(e.pointerId.toString(), e);
  70157. }
  70158. else {
  70159. // You can only trigger the action buttons with a joystick declared
  70160. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  70161. this._action();
  70162. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  70163. }
  70164. }
  70165. };
  70166. VirtualJoystick.prototype._onPointerMove = function (e) {
  70167. // If the current pointer is the one associated to the joystick (first touch contact)
  70168. if (this._joystickPointerID == e.pointerId) {
  70169. this._joystickPointerPos.x = e.clientX;
  70170. this._joystickPointerPos.y = e.clientY;
  70171. this._deltaJoystickVector = this._joystickPointerPos.clone();
  70172. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  70173. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  70174. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  70175. switch (this._axisTargetedByLeftAndRight) {
  70176. case JoystickAxis.X:
  70177. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  70178. break;
  70179. case JoystickAxis.Y:
  70180. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  70181. break;
  70182. case JoystickAxis.Z:
  70183. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  70184. break;
  70185. }
  70186. var directionUpDown = this.reverseUpDown ? 1 : -1;
  70187. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  70188. switch (this._axisTargetedByUpAndDown) {
  70189. case JoystickAxis.X:
  70190. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  70191. break;
  70192. case JoystickAxis.Y:
  70193. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  70194. break;
  70195. case JoystickAxis.Z:
  70196. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  70197. break;
  70198. }
  70199. }
  70200. else {
  70201. var data = this._touches.get(e.pointerId.toString());
  70202. if (data) {
  70203. data.x = e.clientX;
  70204. data.y = e.clientY;
  70205. }
  70206. }
  70207. };
  70208. VirtualJoystick.prototype._onPointerUp = function (e) {
  70209. if (this._joystickPointerID == e.pointerId) {
  70210. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  70211. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  70212. this._joystickPointerID = -1;
  70213. this.pressed = false;
  70214. }
  70215. else {
  70216. var touch = this._touches.get(e.pointerId.toString());
  70217. if (touch) {
  70218. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70219. }
  70220. }
  70221. this._deltaJoystickVector.x = 0;
  70222. this._deltaJoystickVector.y = 0;
  70223. this._touches.remove(e.pointerId.toString());
  70224. };
  70225. /**
  70226. * Change the color of the virtual joystick
  70227. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  70228. */
  70229. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  70230. this._joystickColor = newColor;
  70231. };
  70232. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  70233. this._action = action;
  70234. };
  70235. // Define which axis you'd like to control for left & right
  70236. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  70237. switch (axis) {
  70238. case JoystickAxis.X:
  70239. case JoystickAxis.Y:
  70240. case JoystickAxis.Z:
  70241. this._axisTargetedByLeftAndRight = axis;
  70242. break;
  70243. default:
  70244. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70245. break;
  70246. }
  70247. };
  70248. // Define which axis you'd like to control for up & down
  70249. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  70250. switch (axis) {
  70251. case JoystickAxis.X:
  70252. case JoystickAxis.Y:
  70253. case JoystickAxis.Z:
  70254. this._axisTargetedByUpAndDown = axis;
  70255. break;
  70256. default:
  70257. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70258. break;
  70259. }
  70260. };
  70261. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  70262. var _this = this;
  70263. if (this.pressed) {
  70264. this._touches.forEach(function (key, touch) {
  70265. if (touch.pointerId === _this._joystickPointerID) {
  70266. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  70267. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  70268. VirtualJoystick.vjCanvasContext.beginPath();
  70269. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70270. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70271. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  70272. VirtualJoystick.vjCanvasContext.stroke();
  70273. VirtualJoystick.vjCanvasContext.closePath();
  70274. VirtualJoystick.vjCanvasContext.beginPath();
  70275. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70276. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70277. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  70278. VirtualJoystick.vjCanvasContext.stroke();
  70279. VirtualJoystick.vjCanvasContext.closePath();
  70280. VirtualJoystick.vjCanvasContext.beginPath();
  70281. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70282. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  70283. VirtualJoystick.vjCanvasContext.stroke();
  70284. VirtualJoystick.vjCanvasContext.closePath();
  70285. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  70286. }
  70287. else {
  70288. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70289. VirtualJoystick.vjCanvasContext.beginPath();
  70290. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  70291. VirtualJoystick.vjCanvasContext.beginPath();
  70292. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  70293. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70294. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  70295. VirtualJoystick.vjCanvasContext.stroke();
  70296. VirtualJoystick.vjCanvasContext.closePath();
  70297. touch.prevX = touch.x;
  70298. touch.prevY = touch.y;
  70299. }
  70300. ;
  70301. });
  70302. }
  70303. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70304. };
  70305. VirtualJoystick.prototype.releaseCanvas = function () {
  70306. if (VirtualJoystick.vjCanvas) {
  70307. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  70308. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  70309. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  70310. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  70311. window.removeEventListener("resize", this._onResize);
  70312. document.body.removeChild(VirtualJoystick.vjCanvas);
  70313. VirtualJoystick.vjCanvas = null;
  70314. }
  70315. };
  70316. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  70317. VirtualJoystick._globalJoystickIndex = 0;
  70318. return VirtualJoystick;
  70319. }());
  70320. BABYLON.VirtualJoystick = VirtualJoystick;
  70321. })(BABYLON || (BABYLON = {}));
  70322. //# sourceMappingURL=babylon.virtualJoystick.js.map
  70323. var BABYLON;
  70324. (function (BABYLON) {
  70325. // We're mainly based on the logic defined into the FreeCamera code
  70326. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  70327. __extends(VirtualJoysticksCamera, _super);
  70328. function VirtualJoysticksCamera(name, position, scene) {
  70329. var _this = _super.call(this, name, position, scene) || this;
  70330. _this.inputs.addVirtualJoystick();
  70331. return _this;
  70332. }
  70333. VirtualJoysticksCamera.prototype.getClassName = function () {
  70334. return "VirtualJoysticksCamera";
  70335. };
  70336. return VirtualJoysticksCamera;
  70337. }(BABYLON.FreeCamera));
  70338. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  70339. })(BABYLON || (BABYLON = {}));
  70340. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  70341. var BABYLON;
  70342. (function (BABYLON) {
  70343. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  70344. function FreeCameraVirtualJoystickInput() {
  70345. }
  70346. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  70347. return this._leftjoystick;
  70348. };
  70349. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  70350. return this._rightjoystick;
  70351. };
  70352. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  70353. if (this._leftjoystick) {
  70354. var camera = this.camera;
  70355. var speed = camera._computeLocalCameraSpeed() * 50;
  70356. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  70357. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  70358. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  70359. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  70360. if (!this._leftjoystick.pressed) {
  70361. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  70362. }
  70363. if (!this._rightjoystick.pressed) {
  70364. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  70365. }
  70366. }
  70367. };
  70368. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  70369. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  70370. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  70371. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  70372. this._leftjoystick.setJoystickSensibility(0.15);
  70373. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  70374. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  70375. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  70376. this._rightjoystick.reverseUpDown = true;
  70377. this._rightjoystick.setJoystickSensibility(0.05);
  70378. this._rightjoystick.setJoystickColor("yellow");
  70379. };
  70380. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  70381. this._leftjoystick.releaseCanvas();
  70382. this._rightjoystick.releaseCanvas();
  70383. };
  70384. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  70385. return "FreeCameraVirtualJoystickInput";
  70386. };
  70387. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  70388. return "virtualJoystick";
  70389. };
  70390. return FreeCameraVirtualJoystickInput;
  70391. }());
  70392. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  70393. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  70394. })(BABYLON || (BABYLON = {}));
  70395. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  70396. var BABYLON;
  70397. (function (BABYLON) {
  70398. var SimplificationSettings = /** @class */ (function () {
  70399. function SimplificationSettings(quality, distance, optimizeMesh) {
  70400. this.quality = quality;
  70401. this.distance = distance;
  70402. this.optimizeMesh = optimizeMesh;
  70403. }
  70404. return SimplificationSettings;
  70405. }());
  70406. BABYLON.SimplificationSettings = SimplificationSettings;
  70407. var SimplificationQueue = /** @class */ (function () {
  70408. function SimplificationQueue() {
  70409. this.running = false;
  70410. this._simplificationArray = [];
  70411. }
  70412. SimplificationQueue.prototype.addTask = function (task) {
  70413. this._simplificationArray.push(task);
  70414. };
  70415. SimplificationQueue.prototype.executeNext = function () {
  70416. var task = this._simplificationArray.pop();
  70417. if (task) {
  70418. this.running = true;
  70419. this.runSimplification(task);
  70420. }
  70421. else {
  70422. this.running = false;
  70423. }
  70424. };
  70425. SimplificationQueue.prototype.runSimplification = function (task) {
  70426. var _this = this;
  70427. if (task.parallelProcessing) {
  70428. //parallel simplifier
  70429. task.settings.forEach(function (setting) {
  70430. var simplifier = _this.getSimplifier(task);
  70431. simplifier.simplify(setting, function (newMesh) {
  70432. task.mesh.addLODLevel(setting.distance, newMesh);
  70433. newMesh.isVisible = true;
  70434. //check if it is the last
  70435. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  70436. //all done, run the success callback.
  70437. task.successCallback();
  70438. }
  70439. _this.executeNext();
  70440. });
  70441. });
  70442. }
  70443. else {
  70444. //single simplifier.
  70445. var simplifier = this.getSimplifier(task);
  70446. var runDecimation = function (setting, callback) {
  70447. simplifier.simplify(setting, function (newMesh) {
  70448. task.mesh.addLODLevel(setting.distance, newMesh);
  70449. newMesh.isVisible = true;
  70450. //run the next quality level
  70451. callback();
  70452. });
  70453. };
  70454. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  70455. runDecimation(task.settings[loop.index], function () {
  70456. loop.executeNext();
  70457. });
  70458. }, function () {
  70459. //execution ended, run the success callback.
  70460. if (task.successCallback) {
  70461. task.successCallback();
  70462. }
  70463. _this.executeNext();
  70464. });
  70465. }
  70466. };
  70467. SimplificationQueue.prototype.getSimplifier = function (task) {
  70468. switch (task.simplificationType) {
  70469. case SimplificationType.QUADRATIC:
  70470. default:
  70471. return new QuadraticErrorSimplification(task.mesh);
  70472. }
  70473. };
  70474. return SimplificationQueue;
  70475. }());
  70476. BABYLON.SimplificationQueue = SimplificationQueue;
  70477. /**
  70478. * The implemented types of simplification.
  70479. * At the moment only Quadratic Error Decimation is implemented.
  70480. */
  70481. var SimplificationType;
  70482. (function (SimplificationType) {
  70483. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  70484. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  70485. var DecimationTriangle = /** @class */ (function () {
  70486. function DecimationTriangle(vertices) {
  70487. this.vertices = vertices;
  70488. this.error = new Array(4);
  70489. this.deleted = false;
  70490. this.isDirty = false;
  70491. this.deletePending = false;
  70492. this.borderFactor = 0;
  70493. }
  70494. return DecimationTriangle;
  70495. }());
  70496. BABYLON.DecimationTriangle = DecimationTriangle;
  70497. var DecimationVertex = /** @class */ (function () {
  70498. function DecimationVertex(position, id) {
  70499. this.position = position;
  70500. this.id = id;
  70501. this.isBorder = true;
  70502. this.q = new QuadraticMatrix();
  70503. this.triangleCount = 0;
  70504. this.triangleStart = 0;
  70505. this.originalOffsets = [];
  70506. }
  70507. DecimationVertex.prototype.updatePosition = function (newPosition) {
  70508. this.position.copyFrom(newPosition);
  70509. };
  70510. return DecimationVertex;
  70511. }());
  70512. BABYLON.DecimationVertex = DecimationVertex;
  70513. var QuadraticMatrix = /** @class */ (function () {
  70514. function QuadraticMatrix(data) {
  70515. this.data = new Array(10);
  70516. for (var i = 0; i < 10; ++i) {
  70517. if (data && data[i]) {
  70518. this.data[i] = data[i];
  70519. }
  70520. else {
  70521. this.data[i] = 0;
  70522. }
  70523. }
  70524. }
  70525. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  70526. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  70527. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  70528. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  70529. return det;
  70530. };
  70531. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  70532. for (var i = 0; i < 10; ++i) {
  70533. this.data[i] += matrix.data[i];
  70534. }
  70535. };
  70536. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  70537. for (var i = 0; i < 10; ++i) {
  70538. this.data[i] += data[i];
  70539. }
  70540. };
  70541. QuadraticMatrix.prototype.add = function (matrix) {
  70542. var m = new QuadraticMatrix();
  70543. for (var i = 0; i < 10; ++i) {
  70544. m.data[i] = this.data[i] + matrix.data[i];
  70545. }
  70546. return m;
  70547. };
  70548. QuadraticMatrix.FromData = function (a, b, c, d) {
  70549. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  70550. };
  70551. //returning an array to avoid garbage collection
  70552. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  70553. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  70554. };
  70555. return QuadraticMatrix;
  70556. }());
  70557. BABYLON.QuadraticMatrix = QuadraticMatrix;
  70558. var Reference = /** @class */ (function () {
  70559. function Reference(vertexId, triangleId) {
  70560. this.vertexId = vertexId;
  70561. this.triangleId = triangleId;
  70562. }
  70563. return Reference;
  70564. }());
  70565. BABYLON.Reference = Reference;
  70566. /**
  70567. * An implementation of the Quadratic Error simplification algorithm.
  70568. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  70569. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  70570. * @author RaananW
  70571. */
  70572. var QuadraticErrorSimplification = /** @class */ (function () {
  70573. function QuadraticErrorSimplification(_mesh) {
  70574. this._mesh = _mesh;
  70575. this.initialized = false;
  70576. this.syncIterations = 5000;
  70577. this.aggressiveness = 7;
  70578. this.decimationIterations = 100;
  70579. this.boundingBoxEpsilon = BABYLON.Epsilon;
  70580. }
  70581. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  70582. var _this = this;
  70583. this.initDecimatedMesh();
  70584. //iterating through the submeshes array, one after the other.
  70585. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  70586. _this.initWithMesh(loop.index, function () {
  70587. _this.runDecimation(settings, loop.index, function () {
  70588. loop.executeNext();
  70589. });
  70590. }, settings.optimizeMesh);
  70591. }, function () {
  70592. setTimeout(function () {
  70593. successCallback(_this._reconstructedMesh);
  70594. }, 0);
  70595. });
  70596. };
  70597. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  70598. var _this = this;
  70599. var targetCount = ~~(this.triangles.length * settings.quality);
  70600. var deletedTriangles = 0;
  70601. var triangleCount = this.triangles.length;
  70602. var iterationFunction = function (iteration, callback) {
  70603. setTimeout(function () {
  70604. if (iteration % 5 === 0) {
  70605. _this.updateMesh(iteration === 0);
  70606. }
  70607. for (var i = 0; i < _this.triangles.length; ++i) {
  70608. _this.triangles[i].isDirty = false;
  70609. }
  70610. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  70611. var trianglesIterator = function (i) {
  70612. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  70613. var t = _this.triangles[tIdx];
  70614. if (!t)
  70615. return;
  70616. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  70617. return;
  70618. }
  70619. for (var j = 0; j < 3; ++j) {
  70620. if (t.error[j] < threshold) {
  70621. var deleted0 = [];
  70622. var deleted1 = [];
  70623. var v0 = t.vertices[j];
  70624. var v1 = t.vertices[(j + 1) % 3];
  70625. if (v0.isBorder || v1.isBorder)
  70626. continue;
  70627. var p = BABYLON.Vector3.Zero();
  70628. var n = BABYLON.Vector3.Zero();
  70629. var uv = BABYLON.Vector2.Zero();
  70630. var color = new BABYLON.Color4(0, 0, 0, 1);
  70631. _this.calculateError(v0, v1, p, n, uv, color);
  70632. var delTr = new Array();
  70633. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  70634. continue;
  70635. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  70636. continue;
  70637. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  70638. continue;
  70639. var uniqueArray = new Array();
  70640. delTr.forEach(function (deletedT) {
  70641. if (uniqueArray.indexOf(deletedT) === -1) {
  70642. deletedT.deletePending = true;
  70643. uniqueArray.push(deletedT);
  70644. }
  70645. });
  70646. if (uniqueArray.length % 2 !== 0) {
  70647. continue;
  70648. }
  70649. v0.q = v1.q.add(v0.q);
  70650. v0.updatePosition(p);
  70651. var tStart = _this.references.length;
  70652. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  70653. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  70654. var tCount = _this.references.length - tStart;
  70655. if (tCount <= v0.triangleCount) {
  70656. if (tCount) {
  70657. for (var c = 0; c < tCount; c++) {
  70658. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  70659. }
  70660. }
  70661. }
  70662. else {
  70663. v0.triangleStart = tStart;
  70664. }
  70665. v0.triangleCount = tCount;
  70666. break;
  70667. }
  70668. }
  70669. };
  70670. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  70671. }, 0);
  70672. };
  70673. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  70674. if (triangleCount - deletedTriangles <= targetCount)
  70675. loop.breakLoop();
  70676. else {
  70677. iterationFunction(loop.index, function () {
  70678. loop.executeNext();
  70679. });
  70680. }
  70681. }, function () {
  70682. setTimeout(function () {
  70683. //reconstruct this part of the mesh
  70684. _this.reconstructMesh(submeshIndex);
  70685. successCallback();
  70686. }, 0);
  70687. });
  70688. };
  70689. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  70690. var _this = this;
  70691. this.vertices = [];
  70692. this.triangles = [];
  70693. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70694. var indices = this._mesh.getIndices();
  70695. var submesh = this._mesh.subMeshes[submeshIndex];
  70696. var findInVertices = function (positionToSearch) {
  70697. if (optimizeMesh) {
  70698. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  70699. if (_this.vertices[ii].position.equals(positionToSearch)) {
  70700. return _this.vertices[ii];
  70701. }
  70702. }
  70703. }
  70704. return null;
  70705. };
  70706. var vertexReferences = [];
  70707. var vertexInit = function (i) {
  70708. if (!positionData) {
  70709. return;
  70710. }
  70711. var offset = i + submesh.verticesStart;
  70712. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  70713. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  70714. vertex.originalOffsets.push(offset);
  70715. if (vertex.id === _this.vertices.length) {
  70716. _this.vertices.push(vertex);
  70717. }
  70718. vertexReferences.push(vertex.id);
  70719. };
  70720. //var totalVertices = mesh.getTotalVertices();
  70721. var totalVertices = submesh.verticesCount;
  70722. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  70723. var indicesInit = function (i) {
  70724. if (!indices) {
  70725. return;
  70726. }
  70727. var offset = (submesh.indexStart / 3) + i;
  70728. var pos = (offset * 3);
  70729. var i0 = indices[pos + 0];
  70730. var i1 = indices[pos + 1];
  70731. var i2 = indices[pos + 2];
  70732. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  70733. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  70734. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  70735. var triangle = new DecimationTriangle([v0, v1, v2]);
  70736. triangle.originalOffset = pos;
  70737. _this.triangles.push(triangle);
  70738. };
  70739. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  70740. _this.init(callback);
  70741. });
  70742. });
  70743. };
  70744. QuadraticErrorSimplification.prototype.init = function (callback) {
  70745. var _this = this;
  70746. var triangleInit1 = function (i) {
  70747. var t = _this.triangles[i];
  70748. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  70749. for (var j = 0; j < 3; j++) {
  70750. 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))));
  70751. }
  70752. };
  70753. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  70754. var triangleInit2 = function (i) {
  70755. var t = _this.triangles[i];
  70756. for (var j = 0; j < 3; ++j) {
  70757. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  70758. }
  70759. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70760. };
  70761. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  70762. _this.initialized = true;
  70763. callback();
  70764. });
  70765. });
  70766. };
  70767. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  70768. var newTriangles = [];
  70769. var i;
  70770. for (i = 0; i < this.vertices.length; ++i) {
  70771. this.vertices[i].triangleCount = 0;
  70772. }
  70773. var t;
  70774. var j;
  70775. for (i = 0; i < this.triangles.length; ++i) {
  70776. if (!this.triangles[i].deleted) {
  70777. t = this.triangles[i];
  70778. for (j = 0; j < 3; ++j) {
  70779. t.vertices[j].triangleCount = 1;
  70780. }
  70781. newTriangles.push(t);
  70782. }
  70783. }
  70784. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  70785. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  70786. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  70787. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  70788. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  70789. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70790. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  70791. var vertexCount = 0;
  70792. for (i = 0; i < this.vertices.length; ++i) {
  70793. var vertex = this.vertices[i];
  70794. vertex.id = vertexCount;
  70795. if (vertex.triangleCount) {
  70796. vertex.originalOffsets.forEach(function (originalOffset) {
  70797. if (!normalData) {
  70798. return;
  70799. }
  70800. newPositionData.push(vertex.position.x);
  70801. newPositionData.push(vertex.position.y);
  70802. newPositionData.push(vertex.position.z);
  70803. newNormalData.push(normalData[originalOffset * 3]);
  70804. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  70805. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  70806. if (uvs && uvs.length) {
  70807. newUVsData.push(uvs[(originalOffset * 2)]);
  70808. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  70809. }
  70810. else if (colorsData && colorsData.length) {
  70811. newColorsData.push(colorsData[(originalOffset * 4)]);
  70812. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  70813. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  70814. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  70815. }
  70816. ++vertexCount;
  70817. });
  70818. }
  70819. }
  70820. var startingIndex = this._reconstructedMesh.getTotalIndices();
  70821. var startingVertex = this._reconstructedMesh.getTotalVertices();
  70822. var submeshesArray = this._reconstructedMesh.subMeshes;
  70823. this._reconstructedMesh.subMeshes = [];
  70824. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  70825. var originalIndices = this._mesh.getIndices();
  70826. for (i = 0; i < newTriangles.length; ++i) {
  70827. t = newTriangles[i]; //now get the new referencing point for each vertex
  70828. [0, 1, 2].forEach(function (idx) {
  70829. var id = originalIndices[t.originalOffset + idx];
  70830. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  70831. if (offset < 0)
  70832. offset = 0;
  70833. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  70834. });
  70835. }
  70836. //overwriting the old vertex buffers and indices.
  70837. this._reconstructedMesh.setIndices(newIndicesArray);
  70838. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  70839. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  70840. if (newUVsData.length > 0)
  70841. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  70842. if (newColorsData.length > 0)
  70843. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  70844. //create submesh
  70845. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  70846. if (submeshIndex > 0) {
  70847. this._reconstructedMesh.subMeshes = [];
  70848. submeshesArray.forEach(function (submesh) {
  70849. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  70850. });
  70851. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  70852. }
  70853. };
  70854. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  70855. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  70856. this._reconstructedMesh.material = this._mesh.material;
  70857. this._reconstructedMesh.parent = this._mesh.parent;
  70858. this._reconstructedMesh.isVisible = false;
  70859. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  70860. };
  70861. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  70862. for (var i = 0; i < vertex1.triangleCount; ++i) {
  70863. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  70864. if (t.deleted)
  70865. continue;
  70866. var s = this.references[vertex1.triangleStart + i].vertexId;
  70867. var v1 = t.vertices[(s + 1) % 3];
  70868. var v2 = t.vertices[(s + 2) % 3];
  70869. if ((v1 === vertex2 || v2 === vertex2)) {
  70870. deletedArray[i] = true;
  70871. delTr.push(t);
  70872. continue;
  70873. }
  70874. var d1 = v1.position.subtract(point);
  70875. d1 = d1.normalize();
  70876. var d2 = v2.position.subtract(point);
  70877. d2 = d2.normalize();
  70878. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  70879. return true;
  70880. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  70881. deletedArray[i] = false;
  70882. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  70883. return true;
  70884. }
  70885. return false;
  70886. };
  70887. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  70888. var newDeleted = deletedTriangles;
  70889. for (var i = 0; i < vertex.triangleCount; ++i) {
  70890. var ref = this.references[vertex.triangleStart + i];
  70891. var t = this.triangles[ref.triangleId];
  70892. if (t.deleted)
  70893. continue;
  70894. if (deletedArray[i] && t.deletePending) {
  70895. t.deleted = true;
  70896. newDeleted++;
  70897. continue;
  70898. }
  70899. t.vertices[ref.vertexId] = origVertex;
  70900. t.isDirty = true;
  70901. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  70902. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  70903. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  70904. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70905. this.references.push(ref);
  70906. }
  70907. return newDeleted;
  70908. };
  70909. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  70910. for (var i = 0; i < this.vertices.length; ++i) {
  70911. var vCount = [];
  70912. var vId = [];
  70913. var v = this.vertices[i];
  70914. var j;
  70915. for (j = 0; j < v.triangleCount; ++j) {
  70916. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  70917. for (var ii = 0; ii < 3; ii++) {
  70918. var ofs = 0;
  70919. var vv = triangle.vertices[ii];
  70920. while (ofs < vCount.length) {
  70921. if (vId[ofs] === vv.id)
  70922. break;
  70923. ++ofs;
  70924. }
  70925. if (ofs === vCount.length) {
  70926. vCount.push(1);
  70927. vId.push(vv.id);
  70928. }
  70929. else {
  70930. vCount[ofs]++;
  70931. }
  70932. }
  70933. }
  70934. for (j = 0; j < vCount.length; ++j) {
  70935. if (vCount[j] === 1) {
  70936. this.vertices[vId[j]].isBorder = true;
  70937. }
  70938. else {
  70939. this.vertices[vId[j]].isBorder = false;
  70940. }
  70941. }
  70942. }
  70943. };
  70944. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  70945. if (identifyBorders === void 0) { identifyBorders = false; }
  70946. var i;
  70947. if (!identifyBorders) {
  70948. var newTrianglesVector = [];
  70949. for (i = 0; i < this.triangles.length; ++i) {
  70950. if (!this.triangles[i].deleted) {
  70951. newTrianglesVector.push(this.triangles[i]);
  70952. }
  70953. }
  70954. this.triangles = newTrianglesVector;
  70955. }
  70956. for (i = 0; i < this.vertices.length; ++i) {
  70957. this.vertices[i].triangleCount = 0;
  70958. this.vertices[i].triangleStart = 0;
  70959. }
  70960. var t;
  70961. var j;
  70962. var v;
  70963. for (i = 0; i < this.triangles.length; ++i) {
  70964. t = this.triangles[i];
  70965. for (j = 0; j < 3; ++j) {
  70966. v = t.vertices[j];
  70967. v.triangleCount++;
  70968. }
  70969. }
  70970. var tStart = 0;
  70971. for (i = 0; i < this.vertices.length; ++i) {
  70972. this.vertices[i].triangleStart = tStart;
  70973. tStart += this.vertices[i].triangleCount;
  70974. this.vertices[i].triangleCount = 0;
  70975. }
  70976. var newReferences = new Array(this.triangles.length * 3);
  70977. for (i = 0; i < this.triangles.length; ++i) {
  70978. t = this.triangles[i];
  70979. for (j = 0; j < 3; ++j) {
  70980. v = t.vertices[j];
  70981. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  70982. v.triangleCount++;
  70983. }
  70984. }
  70985. this.references = newReferences;
  70986. if (identifyBorders) {
  70987. this.identifyBorder();
  70988. }
  70989. };
  70990. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  70991. var x = point.x;
  70992. var y = point.y;
  70993. var z = point.z;
  70994. 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
  70995. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  70996. };
  70997. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  70998. var q = vertex1.q.add(vertex2.q);
  70999. var border = vertex1.isBorder && vertex2.isBorder;
  71000. var error = 0;
  71001. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  71002. if (qDet !== 0 && !border) {
  71003. if (!pointResult) {
  71004. pointResult = BABYLON.Vector3.Zero();
  71005. }
  71006. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  71007. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  71008. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  71009. error = this.vertexError(q, pointResult);
  71010. }
  71011. else {
  71012. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  71013. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  71014. var error1 = this.vertexError(q, vertex1.position);
  71015. var error2 = this.vertexError(q, vertex2.position);
  71016. var error3 = this.vertexError(q, p3);
  71017. error = Math.min(error1, error2, error3);
  71018. if (error === error1) {
  71019. if (pointResult) {
  71020. pointResult.copyFrom(vertex1.position);
  71021. }
  71022. }
  71023. else if (error === error2) {
  71024. if (pointResult) {
  71025. pointResult.copyFrom(vertex2.position);
  71026. }
  71027. }
  71028. else {
  71029. if (pointResult) {
  71030. pointResult.copyFrom(p3);
  71031. }
  71032. }
  71033. }
  71034. return error;
  71035. };
  71036. return QuadraticErrorSimplification;
  71037. }());
  71038. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  71039. })(BABYLON || (BABYLON = {}));
  71040. //# sourceMappingURL=babylon.meshSimplification.js.map
  71041. var BABYLON;
  71042. (function (BABYLON) {
  71043. var Internals;
  71044. (function (Internals) {
  71045. var MeshLODLevel = /** @class */ (function () {
  71046. function MeshLODLevel(distance, mesh) {
  71047. this.distance = distance;
  71048. this.mesh = mesh;
  71049. }
  71050. return MeshLODLevel;
  71051. }());
  71052. Internals.MeshLODLevel = MeshLODLevel;
  71053. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  71054. })(BABYLON || (BABYLON = {}));
  71055. //# sourceMappingURL=babylon.meshLODLevel.js.map
  71056. var BABYLON;
  71057. (function (BABYLON) {
  71058. // Standard optimizations
  71059. var SceneOptimization = /** @class */ (function () {
  71060. function SceneOptimization(priority) {
  71061. if (priority === void 0) { priority = 0; }
  71062. this.priority = priority;
  71063. this.apply = function (scene) {
  71064. return true; // Return true if everything that can be done was applied
  71065. };
  71066. }
  71067. return SceneOptimization;
  71068. }());
  71069. BABYLON.SceneOptimization = SceneOptimization;
  71070. var TextureOptimization = /** @class */ (function (_super) {
  71071. __extends(TextureOptimization, _super);
  71072. function TextureOptimization(priority, maximumSize) {
  71073. if (priority === void 0) { priority = 0; }
  71074. if (maximumSize === void 0) { maximumSize = 1024; }
  71075. var _this = _super.call(this, priority) || this;
  71076. _this.priority = priority;
  71077. _this.maximumSize = maximumSize;
  71078. _this.apply = function (scene) {
  71079. var allDone = true;
  71080. for (var index = 0; index < scene.textures.length; index++) {
  71081. var texture = scene.textures[index];
  71082. if (!texture.canRescale || texture.getContext) {
  71083. continue;
  71084. }
  71085. var currentSize = texture.getSize();
  71086. var maxDimension = Math.max(currentSize.width, currentSize.height);
  71087. if (maxDimension > _this.maximumSize) {
  71088. texture.scale(0.5);
  71089. allDone = false;
  71090. }
  71091. }
  71092. return allDone;
  71093. };
  71094. return _this;
  71095. }
  71096. return TextureOptimization;
  71097. }(SceneOptimization));
  71098. BABYLON.TextureOptimization = TextureOptimization;
  71099. var HardwareScalingOptimization = /** @class */ (function (_super) {
  71100. __extends(HardwareScalingOptimization, _super);
  71101. function HardwareScalingOptimization(priority, maximumScale) {
  71102. if (priority === void 0) { priority = 0; }
  71103. if (maximumScale === void 0) { maximumScale = 2; }
  71104. var _this = _super.call(this, priority) || this;
  71105. _this.priority = priority;
  71106. _this.maximumScale = maximumScale;
  71107. _this._currentScale = 1;
  71108. _this.apply = function (scene) {
  71109. _this._currentScale++;
  71110. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  71111. return _this._currentScale >= _this.maximumScale;
  71112. };
  71113. return _this;
  71114. }
  71115. return HardwareScalingOptimization;
  71116. }(SceneOptimization));
  71117. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  71118. var ShadowsOptimization = /** @class */ (function (_super) {
  71119. __extends(ShadowsOptimization, _super);
  71120. function ShadowsOptimization() {
  71121. var _this = _super !== null && _super.apply(this, arguments) || this;
  71122. _this.apply = function (scene) {
  71123. scene.shadowsEnabled = false;
  71124. return true;
  71125. };
  71126. return _this;
  71127. }
  71128. return ShadowsOptimization;
  71129. }(SceneOptimization));
  71130. BABYLON.ShadowsOptimization = ShadowsOptimization;
  71131. var PostProcessesOptimization = /** @class */ (function (_super) {
  71132. __extends(PostProcessesOptimization, _super);
  71133. function PostProcessesOptimization() {
  71134. var _this = _super !== null && _super.apply(this, arguments) || this;
  71135. _this.apply = function (scene) {
  71136. scene.postProcessesEnabled = false;
  71137. return true;
  71138. };
  71139. return _this;
  71140. }
  71141. return PostProcessesOptimization;
  71142. }(SceneOptimization));
  71143. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  71144. var LensFlaresOptimization = /** @class */ (function (_super) {
  71145. __extends(LensFlaresOptimization, _super);
  71146. function LensFlaresOptimization() {
  71147. var _this = _super !== null && _super.apply(this, arguments) || this;
  71148. _this.apply = function (scene) {
  71149. scene.lensFlaresEnabled = false;
  71150. return true;
  71151. };
  71152. return _this;
  71153. }
  71154. return LensFlaresOptimization;
  71155. }(SceneOptimization));
  71156. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  71157. var ParticlesOptimization = /** @class */ (function (_super) {
  71158. __extends(ParticlesOptimization, _super);
  71159. function ParticlesOptimization() {
  71160. var _this = _super !== null && _super.apply(this, arguments) || this;
  71161. _this.apply = function (scene) {
  71162. scene.particlesEnabled = false;
  71163. return true;
  71164. };
  71165. return _this;
  71166. }
  71167. return ParticlesOptimization;
  71168. }(SceneOptimization));
  71169. BABYLON.ParticlesOptimization = ParticlesOptimization;
  71170. var RenderTargetsOptimization = /** @class */ (function (_super) {
  71171. __extends(RenderTargetsOptimization, _super);
  71172. function RenderTargetsOptimization() {
  71173. var _this = _super !== null && _super.apply(this, arguments) || this;
  71174. _this.apply = function (scene) {
  71175. scene.renderTargetsEnabled = false;
  71176. return true;
  71177. };
  71178. return _this;
  71179. }
  71180. return RenderTargetsOptimization;
  71181. }(SceneOptimization));
  71182. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  71183. var MergeMeshesOptimization = /** @class */ (function (_super) {
  71184. __extends(MergeMeshesOptimization, _super);
  71185. function MergeMeshesOptimization() {
  71186. var _this = _super !== null && _super.apply(this, arguments) || this;
  71187. _this._canBeMerged = function (abstractMesh) {
  71188. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  71189. return false;
  71190. }
  71191. var mesh = abstractMesh;
  71192. if (!mesh.isVisible || !mesh.isEnabled()) {
  71193. return false;
  71194. }
  71195. if (mesh.instances.length > 0) {
  71196. return false;
  71197. }
  71198. if (mesh.skeleton || mesh.hasLODLevels) {
  71199. return false;
  71200. }
  71201. if (mesh.parent) {
  71202. return false;
  71203. }
  71204. return true;
  71205. };
  71206. _this.apply = function (scene, updateSelectionTree) {
  71207. var globalPool = scene.meshes.slice(0);
  71208. var globalLength = globalPool.length;
  71209. for (var index = 0; index < globalLength; index++) {
  71210. var currentPool = new Array();
  71211. var current = globalPool[index];
  71212. // Checks
  71213. if (!_this._canBeMerged(current)) {
  71214. continue;
  71215. }
  71216. currentPool.push(current);
  71217. // Find compatible meshes
  71218. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  71219. var otherMesh = globalPool[subIndex];
  71220. if (!_this._canBeMerged(otherMesh)) {
  71221. continue;
  71222. }
  71223. if (otherMesh.material !== current.material) {
  71224. continue;
  71225. }
  71226. if (otherMesh.checkCollisions !== current.checkCollisions) {
  71227. continue;
  71228. }
  71229. currentPool.push(otherMesh);
  71230. globalLength--;
  71231. globalPool.splice(subIndex, 1);
  71232. subIndex--;
  71233. }
  71234. if (currentPool.length < 2) {
  71235. continue;
  71236. }
  71237. // Merge meshes
  71238. BABYLON.Mesh.MergeMeshes(currentPool);
  71239. }
  71240. if (updateSelectionTree != undefined) {
  71241. if (updateSelectionTree) {
  71242. scene.createOrUpdateSelectionOctree();
  71243. }
  71244. }
  71245. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  71246. scene.createOrUpdateSelectionOctree();
  71247. }
  71248. return true;
  71249. };
  71250. return _this;
  71251. }
  71252. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  71253. get: function () {
  71254. return MergeMeshesOptimization._UpdateSelectionTree;
  71255. },
  71256. set: function (value) {
  71257. MergeMeshesOptimization._UpdateSelectionTree = value;
  71258. },
  71259. enumerable: true,
  71260. configurable: true
  71261. });
  71262. MergeMeshesOptimization._UpdateSelectionTree = false;
  71263. return MergeMeshesOptimization;
  71264. }(SceneOptimization));
  71265. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  71266. // Options
  71267. var SceneOptimizerOptions = /** @class */ (function () {
  71268. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  71269. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  71270. if (trackerDuration === void 0) { trackerDuration = 2000; }
  71271. this.targetFrameRate = targetFrameRate;
  71272. this.trackerDuration = trackerDuration;
  71273. this.optimizations = new Array();
  71274. }
  71275. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  71276. var result = new SceneOptimizerOptions(targetFrameRate);
  71277. var priority = 0;
  71278. result.optimizations.push(new MergeMeshesOptimization(priority));
  71279. result.optimizations.push(new ShadowsOptimization(priority));
  71280. result.optimizations.push(new LensFlaresOptimization(priority));
  71281. // Next priority
  71282. priority++;
  71283. result.optimizations.push(new PostProcessesOptimization(priority));
  71284. result.optimizations.push(new ParticlesOptimization(priority));
  71285. // Next priority
  71286. priority++;
  71287. result.optimizations.push(new TextureOptimization(priority, 1024));
  71288. return result;
  71289. };
  71290. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  71291. var result = new SceneOptimizerOptions(targetFrameRate);
  71292. var priority = 0;
  71293. result.optimizations.push(new MergeMeshesOptimization(priority));
  71294. result.optimizations.push(new ShadowsOptimization(priority));
  71295. result.optimizations.push(new LensFlaresOptimization(priority));
  71296. // Next priority
  71297. priority++;
  71298. result.optimizations.push(new PostProcessesOptimization(priority));
  71299. result.optimizations.push(new ParticlesOptimization(priority));
  71300. // Next priority
  71301. priority++;
  71302. result.optimizations.push(new TextureOptimization(priority, 512));
  71303. // Next priority
  71304. priority++;
  71305. result.optimizations.push(new RenderTargetsOptimization(priority));
  71306. // Next priority
  71307. priority++;
  71308. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  71309. return result;
  71310. };
  71311. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  71312. var result = new SceneOptimizerOptions(targetFrameRate);
  71313. var priority = 0;
  71314. result.optimizations.push(new MergeMeshesOptimization(priority));
  71315. result.optimizations.push(new ShadowsOptimization(priority));
  71316. result.optimizations.push(new LensFlaresOptimization(priority));
  71317. // Next priority
  71318. priority++;
  71319. result.optimizations.push(new PostProcessesOptimization(priority));
  71320. result.optimizations.push(new ParticlesOptimization(priority));
  71321. // Next priority
  71322. priority++;
  71323. result.optimizations.push(new TextureOptimization(priority, 256));
  71324. // Next priority
  71325. priority++;
  71326. result.optimizations.push(new RenderTargetsOptimization(priority));
  71327. // Next priority
  71328. priority++;
  71329. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  71330. return result;
  71331. };
  71332. return SceneOptimizerOptions;
  71333. }());
  71334. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  71335. // Scene optimizer tool
  71336. var SceneOptimizer = /** @class */ (function () {
  71337. function SceneOptimizer() {
  71338. }
  71339. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  71340. // TODO: add an epsilon
  71341. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  71342. if (onSuccess) {
  71343. onSuccess();
  71344. }
  71345. return;
  71346. }
  71347. // Apply current level of optimizations
  71348. var allDone = true;
  71349. var noOptimizationApplied = true;
  71350. for (var index = 0; index < options.optimizations.length; index++) {
  71351. var optimization = options.optimizations[index];
  71352. if (optimization.priority === currentPriorityLevel) {
  71353. noOptimizationApplied = false;
  71354. allDone = allDone && optimization.apply(scene);
  71355. }
  71356. }
  71357. // If no optimization was applied, this is a failure :(
  71358. if (noOptimizationApplied) {
  71359. if (onFailure) {
  71360. onFailure();
  71361. }
  71362. return;
  71363. }
  71364. // If all optimizations were done, move to next level
  71365. if (allDone) {
  71366. currentPriorityLevel++;
  71367. }
  71368. // Let's the system running for a specific amount of time before checking FPS
  71369. scene.executeWhenReady(function () {
  71370. setTimeout(function () {
  71371. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  71372. }, options.trackerDuration);
  71373. });
  71374. };
  71375. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  71376. if (!options) {
  71377. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  71378. }
  71379. // Let's the system running for a specific amount of time before checking FPS
  71380. scene.executeWhenReady(function () {
  71381. setTimeout(function () {
  71382. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  71383. }, options.trackerDuration);
  71384. });
  71385. };
  71386. return SceneOptimizer;
  71387. }());
  71388. BABYLON.SceneOptimizer = SceneOptimizer;
  71389. })(BABYLON || (BABYLON = {}));
  71390. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  71391. var BABYLON;
  71392. (function (BABYLON) {
  71393. var OutlineRenderer = /** @class */ (function () {
  71394. function OutlineRenderer(scene) {
  71395. this.zOffset = 1;
  71396. this._scene = scene;
  71397. }
  71398. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  71399. var _this = this;
  71400. if (useOverlay === void 0) { useOverlay = false; }
  71401. var scene = this._scene;
  71402. var engine = this._scene.getEngine();
  71403. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71404. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  71405. return;
  71406. }
  71407. var mesh = subMesh.getRenderingMesh();
  71408. var material = subMesh.getMaterial();
  71409. if (!material || !scene.activeCamera) {
  71410. return;
  71411. }
  71412. engine.enableEffect(this._effect);
  71413. // Logarithmic depth
  71414. if (material.useLogarithmicDepth) {
  71415. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  71416. }
  71417. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  71418. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  71419. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71420. // Bones
  71421. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71422. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71423. }
  71424. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71425. // Alpha test
  71426. if (material && material.needAlphaTesting()) {
  71427. var alphaTexture = material.getAlphaTestTexture();
  71428. if (alphaTexture) {
  71429. this._effect.setTexture("diffuseSampler", alphaTexture);
  71430. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71431. }
  71432. }
  71433. engine.setZOffset(-this.zOffset);
  71434. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  71435. engine.setZOffset(0);
  71436. };
  71437. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  71438. var defines = [];
  71439. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71440. var mesh = subMesh.getMesh();
  71441. var material = subMesh.getMaterial();
  71442. if (material) {
  71443. // Alpha test
  71444. if (material.needAlphaTesting()) {
  71445. defines.push("#define ALPHATEST");
  71446. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71447. attribs.push(BABYLON.VertexBuffer.UVKind);
  71448. defines.push("#define UV1");
  71449. }
  71450. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71451. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71452. defines.push("#define UV2");
  71453. }
  71454. }
  71455. //Logarithmic depth
  71456. if (material.useLogarithmicDepth) {
  71457. defines.push("#define LOGARITHMICDEPTH");
  71458. }
  71459. }
  71460. // Bones
  71461. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71462. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71463. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71464. if (mesh.numBoneInfluencers > 4) {
  71465. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71466. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71467. }
  71468. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71469. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71470. }
  71471. else {
  71472. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71473. }
  71474. // Instances
  71475. if (useInstances) {
  71476. defines.push("#define INSTANCES");
  71477. attribs.push("world0");
  71478. attribs.push("world1");
  71479. attribs.push("world2");
  71480. attribs.push("world3");
  71481. }
  71482. // Get correct effect
  71483. var join = defines.join("\n");
  71484. if (this._cachedDefines !== join) {
  71485. this._cachedDefines = join;
  71486. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  71487. }
  71488. return this._effect.isReady();
  71489. };
  71490. return OutlineRenderer;
  71491. }());
  71492. BABYLON.OutlineRenderer = OutlineRenderer;
  71493. })(BABYLON || (BABYLON = {}));
  71494. //# sourceMappingURL=babylon.outlineRenderer.js.map
  71495. var BABYLON;
  71496. (function (BABYLON) {
  71497. var FaceAdjacencies = /** @class */ (function () {
  71498. function FaceAdjacencies() {
  71499. this.edges = new Array();
  71500. this.edgesConnectedCount = 0;
  71501. }
  71502. return FaceAdjacencies;
  71503. }());
  71504. var EdgesRenderer = /** @class */ (function () {
  71505. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  71506. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  71507. if (epsilon === void 0) { epsilon = 0.95; }
  71508. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  71509. this.edgesWidthScalerForOrthographic = 1000.0;
  71510. this.edgesWidthScalerForPerspective = 50.0;
  71511. this._linesPositions = new Array();
  71512. this._linesNormals = new Array();
  71513. this._linesIndices = new Array();
  71514. this._buffers = {};
  71515. this._checkVerticesInsteadOfIndices = false;
  71516. this._source = source;
  71517. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  71518. this._epsilon = epsilon;
  71519. this._prepareRessources();
  71520. this._generateEdgesLines();
  71521. }
  71522. EdgesRenderer.prototype._prepareRessources = function () {
  71523. if (this._lineShader) {
  71524. return;
  71525. }
  71526. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  71527. attributes: ["position", "normal"],
  71528. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  71529. });
  71530. this._lineShader.disableDepthWrite = true;
  71531. this._lineShader.backFaceCulling = false;
  71532. };
  71533. EdgesRenderer.prototype._rebuild = function () {
  71534. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71535. if (buffer) {
  71536. buffer._rebuild();
  71537. }
  71538. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71539. if (buffer) {
  71540. buffer._rebuild();
  71541. }
  71542. var scene = this._source.getScene();
  71543. var engine = scene.getEngine();
  71544. this._ib = engine.createIndexBuffer(this._linesIndices);
  71545. };
  71546. EdgesRenderer.prototype.dispose = function () {
  71547. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71548. if (buffer) {
  71549. buffer.dispose();
  71550. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  71551. }
  71552. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71553. if (buffer) {
  71554. buffer.dispose();
  71555. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  71556. }
  71557. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  71558. this._lineShader.dispose();
  71559. };
  71560. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  71561. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  71562. return 0;
  71563. }
  71564. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  71565. return 1;
  71566. }
  71567. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  71568. return 2;
  71569. }
  71570. return -1;
  71571. };
  71572. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  71573. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  71574. return 0;
  71575. }
  71576. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  71577. return 1;
  71578. }
  71579. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  71580. return 2;
  71581. }
  71582. return -1;
  71583. };
  71584. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  71585. var needToCreateLine;
  71586. if (edge === undefined) {
  71587. needToCreateLine = true;
  71588. }
  71589. else {
  71590. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  71591. needToCreateLine = dotProduct < this._epsilon;
  71592. }
  71593. if (needToCreateLine) {
  71594. var offset = this._linesPositions.length / 3;
  71595. var normal = p0.subtract(p1);
  71596. normal.normalize();
  71597. // Positions
  71598. this._linesPositions.push(p0.x);
  71599. this._linesPositions.push(p0.y);
  71600. this._linesPositions.push(p0.z);
  71601. this._linesPositions.push(p0.x);
  71602. this._linesPositions.push(p0.y);
  71603. this._linesPositions.push(p0.z);
  71604. this._linesPositions.push(p1.x);
  71605. this._linesPositions.push(p1.y);
  71606. this._linesPositions.push(p1.z);
  71607. this._linesPositions.push(p1.x);
  71608. this._linesPositions.push(p1.y);
  71609. this._linesPositions.push(p1.z);
  71610. // Normals
  71611. this._linesNormals.push(p1.x);
  71612. this._linesNormals.push(p1.y);
  71613. this._linesNormals.push(p1.z);
  71614. this._linesNormals.push(-1);
  71615. this._linesNormals.push(p1.x);
  71616. this._linesNormals.push(p1.y);
  71617. this._linesNormals.push(p1.z);
  71618. this._linesNormals.push(1);
  71619. this._linesNormals.push(p0.x);
  71620. this._linesNormals.push(p0.y);
  71621. this._linesNormals.push(p0.z);
  71622. this._linesNormals.push(-1);
  71623. this._linesNormals.push(p0.x);
  71624. this._linesNormals.push(p0.y);
  71625. this._linesNormals.push(p0.z);
  71626. this._linesNormals.push(1);
  71627. // Indices
  71628. this._linesIndices.push(offset);
  71629. this._linesIndices.push(offset + 1);
  71630. this._linesIndices.push(offset + 2);
  71631. this._linesIndices.push(offset);
  71632. this._linesIndices.push(offset + 2);
  71633. this._linesIndices.push(offset + 3);
  71634. }
  71635. };
  71636. EdgesRenderer.prototype._generateEdgesLines = function () {
  71637. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71638. var indices = this._source.getIndices();
  71639. if (!indices || !positions) {
  71640. return;
  71641. }
  71642. // First let's find adjacencies
  71643. var adjacencies = new Array();
  71644. var faceNormals = new Array();
  71645. var index;
  71646. var faceAdjacencies;
  71647. // Prepare faces
  71648. for (index = 0; index < indices.length; index += 3) {
  71649. faceAdjacencies = new FaceAdjacencies();
  71650. var p0Index = indices[index];
  71651. var p1Index = indices[index + 1];
  71652. var p2Index = indices[index + 2];
  71653. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  71654. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  71655. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  71656. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  71657. faceNormal.normalize();
  71658. faceNormals.push(faceNormal);
  71659. adjacencies.push(faceAdjacencies);
  71660. }
  71661. // Scan
  71662. for (index = 0; index < adjacencies.length; index++) {
  71663. faceAdjacencies = adjacencies[index];
  71664. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  71665. var otherFaceAdjacencies = adjacencies[otherIndex];
  71666. if (faceAdjacencies.edgesConnectedCount === 3) {
  71667. break;
  71668. }
  71669. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  71670. continue;
  71671. }
  71672. var otherP0 = indices[otherIndex * 3];
  71673. var otherP1 = indices[otherIndex * 3 + 1];
  71674. var otherP2 = indices[otherIndex * 3 + 2];
  71675. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  71676. var otherEdgeIndex = 0;
  71677. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  71678. continue;
  71679. }
  71680. switch (edgeIndex) {
  71681. case 0:
  71682. if (this._checkVerticesInsteadOfIndices) {
  71683. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71684. }
  71685. else {
  71686. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  71687. }
  71688. break;
  71689. case 1:
  71690. if (this._checkVerticesInsteadOfIndices) {
  71691. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71692. }
  71693. else {
  71694. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  71695. }
  71696. break;
  71697. case 2:
  71698. if (this._checkVerticesInsteadOfIndices) {
  71699. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71700. }
  71701. else {
  71702. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  71703. }
  71704. break;
  71705. }
  71706. if (otherEdgeIndex === -1) {
  71707. continue;
  71708. }
  71709. faceAdjacencies.edges[edgeIndex] = otherIndex;
  71710. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  71711. faceAdjacencies.edgesConnectedCount++;
  71712. otherFaceAdjacencies.edgesConnectedCount++;
  71713. if (faceAdjacencies.edgesConnectedCount === 3) {
  71714. break;
  71715. }
  71716. }
  71717. }
  71718. }
  71719. // Create lines
  71720. for (index = 0; index < adjacencies.length; index++) {
  71721. // 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
  71722. var current = adjacencies[index];
  71723. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  71724. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  71725. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  71726. }
  71727. // Merge into a single mesh
  71728. var engine = this._source.getScene().getEngine();
  71729. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  71730. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  71731. this._ib = engine.createIndexBuffer(this._linesIndices);
  71732. this._indicesCount = this._linesIndices.length;
  71733. };
  71734. EdgesRenderer.prototype.render = function () {
  71735. var scene = this._source.getScene();
  71736. if (!this._lineShader.isReady() || !scene.activeCamera) {
  71737. return;
  71738. }
  71739. var engine = scene.getEngine();
  71740. this._lineShader._preBind();
  71741. // VBOs
  71742. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  71743. scene.resetCachedMaterial();
  71744. this._lineShader.setColor4("color", this._source.edgesColor);
  71745. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  71746. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  71747. }
  71748. else {
  71749. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  71750. }
  71751. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  71752. this._lineShader.bind(this._source.getWorldMatrix());
  71753. // Draw order
  71754. engine.draw(true, 0, this._indicesCount);
  71755. this._lineShader.unbind();
  71756. engine.setDepthWrite(true);
  71757. };
  71758. return EdgesRenderer;
  71759. }());
  71760. BABYLON.EdgesRenderer = EdgesRenderer;
  71761. })(BABYLON || (BABYLON = {}));
  71762. //# sourceMappingURL=babylon.edgesRenderer.js.map
  71763. var BABYLON;
  71764. (function (BABYLON) {
  71765. /**
  71766. * Special Glow Blur post process only blurring the alpha channel
  71767. * It enforces keeping the most luminous color in the color channel.
  71768. */
  71769. var GlowBlurPostProcess = /** @class */ (function (_super) {
  71770. __extends(GlowBlurPostProcess, _super);
  71771. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  71772. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71773. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  71774. _this.direction = direction;
  71775. _this.kernel = kernel;
  71776. _this.onApplyObservable.add(function (effect) {
  71777. effect.setFloat2("screenSize", _this.width, _this.height);
  71778. effect.setVector2("direction", _this.direction);
  71779. effect.setFloat("blurWidth", _this.kernel);
  71780. });
  71781. return _this;
  71782. }
  71783. return GlowBlurPostProcess;
  71784. }(BABYLON.PostProcess));
  71785. /**
  71786. * The highlight layer Helps adding a glow effect around a mesh.
  71787. *
  71788. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  71789. * glowy meshes to your scene.
  71790. *
  71791. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  71792. */
  71793. var HighlightLayer = /** @class */ (function () {
  71794. /**
  71795. * Instantiates a new highlight Layer and references it to the scene..
  71796. * @param name The name of the layer
  71797. * @param scene The scene to use the layer in
  71798. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  71799. */
  71800. function HighlightLayer(name, scene, options) {
  71801. this.name = name;
  71802. this._vertexBuffers = {};
  71803. this._mainTextureDesiredSize = { width: 0, height: 0 };
  71804. this._meshes = {};
  71805. this._maxSize = 0;
  71806. this._shouldRender = false;
  71807. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  71808. this._excludedMeshes = {};
  71809. /**
  71810. * Specifies whether or not the inner glow is ACTIVE in the layer.
  71811. */
  71812. this.innerGlow = true;
  71813. /**
  71814. * Specifies whether or not the outer glow is ACTIVE in the layer.
  71815. */
  71816. this.outerGlow = true;
  71817. /**
  71818. * Specifies wether the highlight layer is enabled or not.
  71819. */
  71820. this.isEnabled = true;
  71821. /**
  71822. * An event triggered when the highlight layer has been disposed.
  71823. * @type {BABYLON.Observable}
  71824. */
  71825. this.onDisposeObservable = new BABYLON.Observable();
  71826. /**
  71827. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  71828. * @type {BABYLON.Observable}
  71829. */
  71830. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  71831. /**
  71832. * An event triggered when the highlight layer is being blurred.
  71833. * @type {BABYLON.Observable}
  71834. */
  71835. this.onBeforeBlurObservable = new BABYLON.Observable();
  71836. /**
  71837. * An event triggered when the highlight layer has been blurred.
  71838. * @type {BABYLON.Observable}
  71839. */
  71840. this.onAfterBlurObservable = new BABYLON.Observable();
  71841. /**
  71842. * An event triggered when the glowing blurred texture is being merged in the scene.
  71843. * @type {BABYLON.Observable}
  71844. */
  71845. this.onBeforeComposeObservable = new BABYLON.Observable();
  71846. /**
  71847. * An event triggered when the glowing blurred texture has been merged in the scene.
  71848. * @type {BABYLON.Observable}
  71849. */
  71850. this.onAfterComposeObservable = new BABYLON.Observable();
  71851. /**
  71852. * An event triggered when the highlight layer changes its size.
  71853. * @type {BABYLON.Observable}
  71854. */
  71855. this.onSizeChangedObservable = new BABYLON.Observable();
  71856. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71857. var engine = scene.getEngine();
  71858. this._engine = engine;
  71859. this._maxSize = this._engine.getCaps().maxTextureSize;
  71860. this._scene.highlightLayers.push(this);
  71861. // Warn on stencil.
  71862. if (!this._engine.isStencilEnable) {
  71863. 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 }");
  71864. }
  71865. // Adapt options
  71866. this._options = options || {
  71867. mainTextureRatio: 0.5,
  71868. blurTextureSizeRatio: 0.5,
  71869. blurHorizontalSize: 1.0,
  71870. blurVerticalSize: 1.0,
  71871. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  71872. camera: null
  71873. };
  71874. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  71875. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  71876. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  71877. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  71878. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  71879. // VBO
  71880. var vertices = [];
  71881. vertices.push(1, 1);
  71882. vertices.push(-1, 1);
  71883. vertices.push(-1, -1);
  71884. vertices.push(1, -1);
  71885. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71886. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71887. this._createIndexBuffer();
  71888. // Effect
  71889. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  71890. // Render target
  71891. this.setMainTextureSize();
  71892. // Create Textures and post processes
  71893. this.createTextureAndPostProcesses();
  71894. }
  71895. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  71896. /**
  71897. * Gets the horizontal size of the blur.
  71898. */
  71899. get: function () {
  71900. return this._horizontalBlurPostprocess.kernel;
  71901. },
  71902. /**
  71903. * Specifies the horizontal size of the blur.
  71904. */
  71905. set: function (value) {
  71906. this._horizontalBlurPostprocess.kernel = value;
  71907. },
  71908. enumerable: true,
  71909. configurable: true
  71910. });
  71911. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  71912. /**
  71913. * Gets the vertical size of the blur.
  71914. */
  71915. get: function () {
  71916. return this._verticalBlurPostprocess.kernel;
  71917. },
  71918. /**
  71919. * Specifies the vertical size of the blur.
  71920. */
  71921. set: function (value) {
  71922. this._verticalBlurPostprocess.kernel = value;
  71923. },
  71924. enumerable: true,
  71925. configurable: true
  71926. });
  71927. Object.defineProperty(HighlightLayer.prototype, "camera", {
  71928. /**
  71929. * Gets the camera attached to the layer.
  71930. */
  71931. get: function () {
  71932. return this._options.camera;
  71933. },
  71934. enumerable: true,
  71935. configurable: true
  71936. });
  71937. HighlightLayer.prototype._createIndexBuffer = function () {
  71938. var engine = this._scene.getEngine();
  71939. // Indices
  71940. var indices = [];
  71941. indices.push(0);
  71942. indices.push(1);
  71943. indices.push(2);
  71944. indices.push(0);
  71945. indices.push(2);
  71946. indices.push(3);
  71947. this._indexBuffer = engine.createIndexBuffer(indices);
  71948. };
  71949. HighlightLayer.prototype._rebuild = function () {
  71950. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71951. if (vb) {
  71952. vb._rebuild();
  71953. }
  71954. this._createIndexBuffer();
  71955. };
  71956. /**
  71957. * Creates the render target textures and post processes used in the highlight layer.
  71958. */
  71959. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  71960. var _this = this;
  71961. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  71962. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  71963. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  71964. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  71965. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  71966. width: this._mainTextureDesiredSize.width,
  71967. height: this._mainTextureDesiredSize.height
  71968. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71969. this._mainTexture.activeCamera = this._options.camera;
  71970. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71971. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71972. this._mainTexture.anisotropicFilteringLevel = 1;
  71973. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71974. this._mainTexture.renderParticles = false;
  71975. this._mainTexture.renderList = null;
  71976. this._mainTexture.ignoreCameraViewport = true;
  71977. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  71978. width: blurTextureWidth,
  71979. height: blurTextureHeight
  71980. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71981. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71982. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71983. this._blurTexture.anisotropicFilteringLevel = 16;
  71984. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71985. this._blurTexture.renderParticles = false;
  71986. this._blurTexture.ignoreCameraViewport = true;
  71987. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71988. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  71989. effect.setTexture("textureSampler", _this._mainTexture);
  71990. });
  71991. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  71992. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71993. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  71994. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71995. });
  71996. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71997. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  71998. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71999. });
  72000. }
  72001. else {
  72002. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72003. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72004. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72005. });
  72006. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72007. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72008. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72009. });
  72010. }
  72011. this._mainTexture.onAfterUnbindObservable.add(function () {
  72012. _this.onBeforeBlurObservable.notifyObservers(_this);
  72013. var internalTexture = _this._blurTexture.getInternalTexture();
  72014. if (internalTexture) {
  72015. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  72016. }
  72017. _this.onAfterBlurObservable.notifyObservers(_this);
  72018. });
  72019. // Custom render function
  72020. var renderSubMesh = function (subMesh) {
  72021. if (!_this._meshes) {
  72022. return;
  72023. }
  72024. var material = subMesh.getMaterial();
  72025. var mesh = subMesh.getRenderingMesh();
  72026. var scene = _this._scene;
  72027. var engine = scene.getEngine();
  72028. if (!material) {
  72029. return;
  72030. }
  72031. // Culling
  72032. engine.setState(material.backFaceCulling);
  72033. // Managing instances
  72034. var batch = mesh._getInstancesRenderList(subMesh._id);
  72035. if (batch.mustReturn) {
  72036. return;
  72037. }
  72038. // Excluded Mesh
  72039. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72040. return;
  72041. }
  72042. ;
  72043. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72044. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  72045. var emissiveTexture = null;
  72046. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  72047. emissiveTexture = material.emissiveTexture;
  72048. }
  72049. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  72050. engine.enableEffect(_this._glowMapGenerationEffect);
  72051. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  72052. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  72053. if (highlightLayerMesh) {
  72054. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  72055. }
  72056. else {
  72057. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  72058. }
  72059. // Alpha test
  72060. if (material && material.needAlphaTesting()) {
  72061. var alphaTexture = material.getAlphaTestTexture();
  72062. if (alphaTexture) {
  72063. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  72064. var textureMatrix = alphaTexture.getTextureMatrix();
  72065. if (textureMatrix) {
  72066. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  72067. }
  72068. }
  72069. }
  72070. // Glow emissive only
  72071. if (emissiveTexture) {
  72072. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  72073. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  72074. }
  72075. // Bones
  72076. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72077. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72078. }
  72079. // Draw
  72080. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  72081. }
  72082. else {
  72083. // Need to reset refresh rate of the shadowMap
  72084. _this._mainTexture.resetRefreshCounter();
  72085. }
  72086. };
  72087. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72088. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  72089. var index;
  72090. var engine = _this._scene.getEngine();
  72091. if (depthOnlySubMeshes.length) {
  72092. engine.setColorWrite(false);
  72093. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72094. renderSubMesh(depthOnlySubMeshes.data[index]);
  72095. }
  72096. engine.setColorWrite(true);
  72097. }
  72098. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72099. renderSubMesh(opaqueSubMeshes.data[index]);
  72100. }
  72101. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72102. renderSubMesh(alphaTestSubMeshes.data[index]);
  72103. }
  72104. for (index = 0; index < transparentSubMeshes.length; index++) {
  72105. renderSubMesh(transparentSubMeshes.data[index]);
  72106. }
  72107. };
  72108. this._mainTexture.onClearObservable.add(function (engine) {
  72109. engine.clear(HighlightLayer.neutralColor, true, true, true);
  72110. });
  72111. };
  72112. /**
  72113. * Checks for the readiness of the element composing the layer.
  72114. * @param subMesh the mesh to check for
  72115. * @param useInstances specify wether or not to use instances to render the mesh
  72116. * @param emissiveTexture the associated emissive texture used to generate the glow
  72117. * @return true if ready otherwise, false
  72118. */
  72119. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  72120. var material = subMesh.getMaterial();
  72121. if (!material) {
  72122. return false;
  72123. }
  72124. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  72125. return false;
  72126. }
  72127. var defines = [];
  72128. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72129. var mesh = subMesh.getMesh();
  72130. var uv1 = false;
  72131. var uv2 = false;
  72132. // Alpha test
  72133. if (material && material.needAlphaTesting()) {
  72134. var alphaTexture = material.getAlphaTestTexture();
  72135. if (alphaTexture) {
  72136. defines.push("#define ALPHATEST");
  72137. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72138. alphaTexture.coordinatesIndex === 1) {
  72139. defines.push("#define DIFFUSEUV2");
  72140. uv2 = true;
  72141. }
  72142. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72143. defines.push("#define DIFFUSEUV1");
  72144. uv1 = true;
  72145. }
  72146. }
  72147. }
  72148. // Emissive
  72149. if (emissiveTexture) {
  72150. defines.push("#define EMISSIVE");
  72151. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72152. emissiveTexture.coordinatesIndex === 1) {
  72153. defines.push("#define EMISSIVEUV2");
  72154. uv2 = true;
  72155. }
  72156. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72157. defines.push("#define EMISSIVEUV1");
  72158. uv1 = true;
  72159. }
  72160. }
  72161. if (uv1) {
  72162. attribs.push(BABYLON.VertexBuffer.UVKind);
  72163. defines.push("#define UV1");
  72164. }
  72165. if (uv2) {
  72166. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72167. defines.push("#define UV2");
  72168. }
  72169. // Bones
  72170. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72171. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72172. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72173. if (mesh.numBoneInfluencers > 4) {
  72174. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72175. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72176. }
  72177. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72178. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72179. }
  72180. else {
  72181. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72182. }
  72183. // Instances
  72184. if (useInstances) {
  72185. defines.push("#define INSTANCES");
  72186. attribs.push("world0");
  72187. attribs.push("world1");
  72188. attribs.push("world2");
  72189. attribs.push("world3");
  72190. }
  72191. // Get correct effect
  72192. var join = defines.join("\n");
  72193. if (this._cachedDefines !== join) {
  72194. this._cachedDefines = join;
  72195. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  72196. }
  72197. return this._glowMapGenerationEffect.isReady();
  72198. };
  72199. /**
  72200. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  72201. */
  72202. HighlightLayer.prototype.render = function () {
  72203. var currentEffect = this._glowMapMergeEffect;
  72204. // Check
  72205. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  72206. return;
  72207. var engine = this._scene.getEngine();
  72208. this.onBeforeComposeObservable.notifyObservers(this);
  72209. // Render
  72210. engine.enableEffect(currentEffect);
  72211. engine.setState(false);
  72212. // Cache
  72213. var previousStencilBuffer = engine.getStencilBuffer();
  72214. var previousStencilFunction = engine.getStencilFunction();
  72215. var previousStencilMask = engine.getStencilMask();
  72216. var previousStencilOperationPass = engine.getStencilOperationPass();
  72217. var previousStencilOperationFail = engine.getStencilOperationFail();
  72218. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  72219. var previousAlphaMode = engine.getAlphaMode();
  72220. // Texture
  72221. currentEffect.setTexture("textureSampler", this._blurTexture);
  72222. // VBOs
  72223. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  72224. // Stencil operations
  72225. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  72226. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  72227. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  72228. // Draw order
  72229. engine.setAlphaMode(this._options.alphaBlendingMode);
  72230. engine.setStencilMask(0x00);
  72231. engine.setStencilBuffer(true);
  72232. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  72233. if (this.outerGlow) {
  72234. currentEffect.setFloat("offset", 0);
  72235. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  72236. engine.draw(true, 0, 6);
  72237. }
  72238. if (this.innerGlow) {
  72239. currentEffect.setFloat("offset", 1);
  72240. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  72241. engine.draw(true, 0, 6);
  72242. }
  72243. // Restore Cache
  72244. engine.setStencilFunction(previousStencilFunction);
  72245. engine.setStencilMask(previousStencilMask);
  72246. engine.setAlphaMode(previousAlphaMode);
  72247. engine.setStencilBuffer(previousStencilBuffer);
  72248. engine.setStencilOperationPass(previousStencilOperationPass);
  72249. engine.setStencilOperationFail(previousStencilOperationFail);
  72250. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  72251. engine._stencilState.reset();
  72252. this.onAfterComposeObservable.notifyObservers(this);
  72253. // Handle size changes.
  72254. var size = this._mainTexture.getSize();
  72255. this.setMainTextureSize();
  72256. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  72257. // Recreate RTT and post processes on size change.
  72258. this.onSizeChangedObservable.notifyObservers(this);
  72259. this.disposeTextureAndPostProcesses();
  72260. this.createTextureAndPostProcesses();
  72261. }
  72262. };
  72263. /**
  72264. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  72265. * @param mesh The mesh to exclude from the highlight layer
  72266. */
  72267. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  72268. if (!this._excludedMeshes) {
  72269. return;
  72270. }
  72271. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72272. if (!meshExcluded) {
  72273. this._excludedMeshes[mesh.uniqueId] = {
  72274. mesh: mesh,
  72275. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  72276. mesh.getEngine().setStencilBuffer(false);
  72277. }),
  72278. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  72279. mesh.getEngine().setStencilBuffer(true);
  72280. }),
  72281. };
  72282. }
  72283. };
  72284. /**
  72285. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  72286. * @param mesh The mesh to highlight
  72287. */
  72288. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  72289. if (!this._excludedMeshes) {
  72290. return;
  72291. }
  72292. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72293. if (meshExcluded) {
  72294. if (meshExcluded.beforeRender) {
  72295. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  72296. }
  72297. if (meshExcluded.afterRender) {
  72298. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  72299. }
  72300. }
  72301. this._excludedMeshes[mesh.uniqueId] = null;
  72302. };
  72303. /**
  72304. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  72305. * @param mesh The mesh to highlight
  72306. * @param color The color of the highlight
  72307. * @param glowEmissiveOnly Extract the glow from the emissive texture
  72308. */
  72309. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  72310. var _this = this;
  72311. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  72312. if (!this._meshes) {
  72313. return;
  72314. }
  72315. var meshHighlight = this._meshes[mesh.uniqueId];
  72316. if (meshHighlight) {
  72317. meshHighlight.color = color;
  72318. }
  72319. else {
  72320. this._meshes[mesh.uniqueId] = {
  72321. mesh: mesh,
  72322. color: color,
  72323. // Lambda required for capture due to Observable this context
  72324. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  72325. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72326. _this.defaultStencilReference(mesh);
  72327. }
  72328. else {
  72329. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  72330. }
  72331. }),
  72332. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  72333. glowEmissiveOnly: glowEmissiveOnly
  72334. };
  72335. }
  72336. this._shouldRender = true;
  72337. };
  72338. /**
  72339. * Remove a mesh from the highlight layer in order to make it stop glowing.
  72340. * @param mesh The mesh to highlight
  72341. */
  72342. HighlightLayer.prototype.removeMesh = function (mesh) {
  72343. if (!this._meshes) {
  72344. return;
  72345. }
  72346. var meshHighlight = this._meshes[mesh.uniqueId];
  72347. if (meshHighlight) {
  72348. if (meshHighlight.observerHighlight) {
  72349. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72350. }
  72351. if (meshHighlight.observerDefault) {
  72352. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72353. }
  72354. }
  72355. this._meshes[mesh.uniqueId] = null;
  72356. this._shouldRender = false;
  72357. for (var meshHighlightToCheck in this._meshes) {
  72358. if (meshHighlightToCheck) {
  72359. this._shouldRender = true;
  72360. break;
  72361. }
  72362. }
  72363. };
  72364. /**
  72365. * Returns true if the layer contains information to display, otherwise false.
  72366. */
  72367. HighlightLayer.prototype.shouldRender = function () {
  72368. return this.isEnabled && this._shouldRender;
  72369. };
  72370. /**
  72371. * Sets the main texture desired size which is the closest power of two
  72372. * of the engine canvas size.
  72373. */
  72374. HighlightLayer.prototype.setMainTextureSize = function () {
  72375. if (this._options.mainTextureFixedSize) {
  72376. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  72377. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  72378. }
  72379. else {
  72380. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  72381. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  72382. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  72383. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  72384. }
  72385. };
  72386. /**
  72387. * Force the stencil to the normal expected value for none glowing parts
  72388. */
  72389. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  72390. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  72391. };
  72392. /**
  72393. * Dispose only the render target textures and post process.
  72394. */
  72395. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  72396. this._blurTexture.dispose();
  72397. this._mainTexture.dispose();
  72398. this._downSamplePostprocess.dispose();
  72399. this._horizontalBlurPostprocess.dispose();
  72400. this._verticalBlurPostprocess.dispose();
  72401. };
  72402. /**
  72403. * Dispose the highlight layer and free resources.
  72404. */
  72405. HighlightLayer.prototype.dispose = function () {
  72406. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72407. if (vertexBuffer) {
  72408. vertexBuffer.dispose();
  72409. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72410. }
  72411. if (this._indexBuffer) {
  72412. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72413. this._indexBuffer = null;
  72414. }
  72415. // Clean textures and post processes
  72416. this.disposeTextureAndPostProcesses();
  72417. if (this._meshes) {
  72418. // Clean mesh references
  72419. for (var id in this._meshes) {
  72420. var meshHighlight = this._meshes[id];
  72421. if (meshHighlight && meshHighlight.mesh) {
  72422. if (meshHighlight.observerHighlight) {
  72423. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72424. }
  72425. if (meshHighlight.observerDefault) {
  72426. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72427. }
  72428. }
  72429. }
  72430. this._meshes = null;
  72431. }
  72432. if (this._excludedMeshes) {
  72433. for (var id in this._excludedMeshes) {
  72434. var meshHighlight = this._excludedMeshes[id];
  72435. if (meshHighlight) {
  72436. if (meshHighlight.beforeRender) {
  72437. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  72438. }
  72439. if (meshHighlight.afterRender) {
  72440. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  72441. }
  72442. }
  72443. }
  72444. this._excludedMeshes = null;
  72445. }
  72446. // Remove from scene
  72447. var index = this._scene.highlightLayers.indexOf(this, 0);
  72448. if (index > -1) {
  72449. this._scene.highlightLayers.splice(index, 1);
  72450. }
  72451. // Callback
  72452. this.onDisposeObservable.notifyObservers(this);
  72453. this.onDisposeObservable.clear();
  72454. this.onBeforeRenderMainTextureObservable.clear();
  72455. this.onBeforeBlurObservable.clear();
  72456. this.onBeforeComposeObservable.clear();
  72457. this.onAfterComposeObservable.clear();
  72458. this.onSizeChangedObservable.clear();
  72459. };
  72460. /**
  72461. * The neutral color used during the preparation of the glow effect.
  72462. * This is black by default as the blend operation is a blend operation.
  72463. */
  72464. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  72465. /**
  72466. * Stencil value used for glowing meshes.
  72467. */
  72468. HighlightLayer.glowingMeshStencilReference = 0x02;
  72469. /**
  72470. * Stencil value used for the other meshes in the scene.
  72471. */
  72472. HighlightLayer.normalMeshStencilReference = 0x01;
  72473. return HighlightLayer;
  72474. }());
  72475. BABYLON.HighlightLayer = HighlightLayer;
  72476. })(BABYLON || (BABYLON = {}));
  72477. //# sourceMappingURL=babylon.highlightlayer.js.map
  72478. var BABYLON;
  72479. (function (BABYLON) {
  72480. var AssetTaskState;
  72481. (function (AssetTaskState) {
  72482. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  72483. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  72484. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  72485. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  72486. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  72487. var AbstractAssetTask = /** @class */ (function () {
  72488. function AbstractAssetTask(name) {
  72489. this.name = name;
  72490. this.isCompleted = false;
  72491. this.taskState = AssetTaskState.INIT;
  72492. }
  72493. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72494. var _this = this;
  72495. this.taskState = AssetTaskState.RUNNING;
  72496. this.runTask(scene, function () {
  72497. _this.onDoneCallback(onSuccess, onError);
  72498. }, function (msg, exception) {
  72499. _this.onErrorCallback(onError, msg, exception);
  72500. });
  72501. };
  72502. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72503. throw new Error("runTask is not implemented");
  72504. };
  72505. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  72506. this.taskState = AssetTaskState.ERROR;
  72507. this.errorObject = {
  72508. message: message,
  72509. exception: exception
  72510. };
  72511. if (this.onError) {
  72512. this.onError(this, message, exception);
  72513. }
  72514. onError();
  72515. };
  72516. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  72517. try {
  72518. this.taskState = AssetTaskState.DONE;
  72519. this.isCompleted = true;
  72520. if (this.onSuccess) {
  72521. this.onSuccess(this);
  72522. }
  72523. onSuccess();
  72524. }
  72525. catch (e) {
  72526. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  72527. }
  72528. };
  72529. return AbstractAssetTask;
  72530. }());
  72531. BABYLON.AbstractAssetTask = AbstractAssetTask;
  72532. var AssetsProgressEvent = /** @class */ (function () {
  72533. function AssetsProgressEvent(remainingCount, totalCount, task) {
  72534. this.remainingCount = remainingCount;
  72535. this.totalCount = totalCount;
  72536. this.task = task;
  72537. }
  72538. return AssetsProgressEvent;
  72539. }());
  72540. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  72541. var MeshAssetTask = /** @class */ (function (_super) {
  72542. __extends(MeshAssetTask, _super);
  72543. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  72544. var _this = _super.call(this, name) || this;
  72545. _this.name = name;
  72546. _this.meshesNames = meshesNames;
  72547. _this.rootUrl = rootUrl;
  72548. _this.sceneFilename = sceneFilename;
  72549. return _this;
  72550. }
  72551. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72552. var _this = this;
  72553. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  72554. _this.loadedMeshes = meshes;
  72555. _this.loadedParticleSystems = particleSystems;
  72556. _this.loadedSkeletons = skeletons;
  72557. onSuccess();
  72558. }, null, function (scene, message, exception) {
  72559. onError(message, exception);
  72560. });
  72561. };
  72562. return MeshAssetTask;
  72563. }(AbstractAssetTask));
  72564. BABYLON.MeshAssetTask = MeshAssetTask;
  72565. var TextFileAssetTask = /** @class */ (function (_super) {
  72566. __extends(TextFileAssetTask, _super);
  72567. function TextFileAssetTask(name, url) {
  72568. var _this = _super.call(this, name) || this;
  72569. _this.name = name;
  72570. _this.url = url;
  72571. return _this;
  72572. }
  72573. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72574. var _this = this;
  72575. BABYLON.Tools.LoadFile(this.url, function (data) {
  72576. _this.text = data;
  72577. onSuccess();
  72578. }, undefined, scene.database, false, function (request, exception) {
  72579. if (request) {
  72580. onError(request.status + " " + request.statusText, exception);
  72581. }
  72582. });
  72583. };
  72584. return TextFileAssetTask;
  72585. }(AbstractAssetTask));
  72586. BABYLON.TextFileAssetTask = TextFileAssetTask;
  72587. var BinaryFileAssetTask = /** @class */ (function (_super) {
  72588. __extends(BinaryFileAssetTask, _super);
  72589. function BinaryFileAssetTask(name, url) {
  72590. var _this = _super.call(this, name) || this;
  72591. _this.name = name;
  72592. _this.url = url;
  72593. return _this;
  72594. }
  72595. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72596. var _this = this;
  72597. BABYLON.Tools.LoadFile(this.url, function (data) {
  72598. _this.data = data;
  72599. onSuccess();
  72600. }, undefined, scene.database, true, function (request, exception) {
  72601. if (request) {
  72602. onError(request.status + " " + request.statusText, exception);
  72603. }
  72604. });
  72605. };
  72606. return BinaryFileAssetTask;
  72607. }(AbstractAssetTask));
  72608. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  72609. var ImageAssetTask = /** @class */ (function (_super) {
  72610. __extends(ImageAssetTask, _super);
  72611. function ImageAssetTask(name, url) {
  72612. var _this = _super.call(this, name) || this;
  72613. _this.name = name;
  72614. _this.url = url;
  72615. return _this;
  72616. }
  72617. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72618. var _this = this;
  72619. var img = new Image();
  72620. BABYLON.Tools.SetCorsBehavior(this.url, img);
  72621. img.onload = function () {
  72622. _this.image = img;
  72623. onSuccess();
  72624. };
  72625. img.onerror = function (err) {
  72626. onError("Error loading image", err);
  72627. };
  72628. img.src = this.url;
  72629. };
  72630. return ImageAssetTask;
  72631. }(AbstractAssetTask));
  72632. BABYLON.ImageAssetTask = ImageAssetTask;
  72633. var TextureAssetTask = /** @class */ (function (_super) {
  72634. __extends(TextureAssetTask, _super);
  72635. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  72636. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72637. var _this = _super.call(this, name) || this;
  72638. _this.name = name;
  72639. _this.url = url;
  72640. _this.noMipmap = noMipmap;
  72641. _this.invertY = invertY;
  72642. _this.samplingMode = samplingMode;
  72643. return _this;
  72644. }
  72645. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72646. var onload = function () {
  72647. onSuccess();
  72648. };
  72649. var onerror = function (msg, exception) {
  72650. onError(msg, exception);
  72651. };
  72652. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  72653. };
  72654. return TextureAssetTask;
  72655. }(AbstractAssetTask));
  72656. BABYLON.TextureAssetTask = TextureAssetTask;
  72657. var CubeTextureAssetTask = /** @class */ (function (_super) {
  72658. __extends(CubeTextureAssetTask, _super);
  72659. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  72660. var _this = _super.call(this, name) || this;
  72661. _this.name = name;
  72662. _this.url = url;
  72663. _this.extensions = extensions;
  72664. _this.noMipmap = noMipmap;
  72665. _this.files = files;
  72666. return _this;
  72667. }
  72668. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72669. var onload = function () {
  72670. onSuccess();
  72671. };
  72672. var onerror = function (msg, exception) {
  72673. onError(msg, exception);
  72674. };
  72675. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  72676. };
  72677. return CubeTextureAssetTask;
  72678. }(AbstractAssetTask));
  72679. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  72680. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  72681. __extends(HDRCubeTextureAssetTask, _super);
  72682. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72683. if (noMipmap === void 0) { noMipmap = false; }
  72684. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72685. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72686. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72687. var _this = _super.call(this, name) || this;
  72688. _this.name = name;
  72689. _this.url = url;
  72690. _this.size = size;
  72691. _this.noMipmap = noMipmap;
  72692. _this.generateHarmonics = generateHarmonics;
  72693. _this.useInGammaSpace = useInGammaSpace;
  72694. _this.usePMREMGenerator = usePMREMGenerator;
  72695. return _this;
  72696. }
  72697. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72698. var onload = function () {
  72699. onSuccess();
  72700. };
  72701. var onerror = function (message, exception) {
  72702. onError(message, exception);
  72703. };
  72704. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  72705. };
  72706. return HDRCubeTextureAssetTask;
  72707. }(AbstractAssetTask));
  72708. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  72709. var AssetsManager = /** @class */ (function () {
  72710. function AssetsManager(scene) {
  72711. this.tasks = new Array();
  72712. this.waitingTasksCount = 0;
  72713. //Observables
  72714. this.onTaskSuccessObservable = new BABYLON.Observable();
  72715. this.onTaskErrorObservable = new BABYLON.Observable();
  72716. this.onTasksDoneObservable = new BABYLON.Observable();
  72717. this.onProgressObservable = new BABYLON.Observable();
  72718. this.useDefaultLoadingScreen = true;
  72719. this._scene = scene;
  72720. }
  72721. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  72722. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  72723. this.tasks.push(task);
  72724. return task;
  72725. };
  72726. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  72727. var task = new TextFileAssetTask(taskName, url);
  72728. this.tasks.push(task);
  72729. return task;
  72730. };
  72731. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  72732. var task = new BinaryFileAssetTask(taskName, url);
  72733. this.tasks.push(task);
  72734. return task;
  72735. };
  72736. AssetsManager.prototype.addImageTask = function (taskName, url) {
  72737. var task = new ImageAssetTask(taskName, url);
  72738. this.tasks.push(task);
  72739. return task;
  72740. };
  72741. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  72742. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72743. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  72744. this.tasks.push(task);
  72745. return task;
  72746. };
  72747. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  72748. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  72749. this.tasks.push(task);
  72750. return task;
  72751. };
  72752. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72753. if (noMipmap === void 0) { noMipmap = false; }
  72754. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72755. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72756. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72757. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  72758. this.tasks.push(task);
  72759. return task;
  72760. };
  72761. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  72762. this.waitingTasksCount--;
  72763. try {
  72764. if (this.onProgress) {
  72765. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  72766. }
  72767. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  72768. }
  72769. catch (e) {
  72770. BABYLON.Tools.Error("Error running progress callbacks.");
  72771. console.log(e);
  72772. }
  72773. if (this.waitingTasksCount === 0) {
  72774. try {
  72775. if (this.onFinish) {
  72776. this.onFinish(this.tasks);
  72777. }
  72778. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72779. }
  72780. catch (e) {
  72781. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  72782. console.log(e);
  72783. }
  72784. this._scene.getEngine().hideLoadingUI();
  72785. }
  72786. };
  72787. AssetsManager.prototype._runTask = function (task) {
  72788. var _this = this;
  72789. var done = function () {
  72790. try {
  72791. if (_this.onTaskSuccess) {
  72792. _this.onTaskSuccess(task);
  72793. }
  72794. _this.onTaskSuccessObservable.notifyObservers(task);
  72795. _this._decreaseWaitingTasksCount(task);
  72796. }
  72797. catch (e) {
  72798. error("Error executing task success callbacks", e);
  72799. }
  72800. };
  72801. var error = function (message, exception) {
  72802. task.errorObject = task.errorObject || {
  72803. message: message,
  72804. exception: exception
  72805. };
  72806. if (_this.onTaskError) {
  72807. _this.onTaskError(task);
  72808. }
  72809. _this.onTaskErrorObservable.notifyObservers(task);
  72810. _this._decreaseWaitingTasksCount(task);
  72811. };
  72812. task.run(this._scene, done, error);
  72813. };
  72814. AssetsManager.prototype.reset = function () {
  72815. this.tasks = new Array();
  72816. return this;
  72817. };
  72818. AssetsManager.prototype.load = function () {
  72819. this.waitingTasksCount = this.tasks.length;
  72820. if (this.waitingTasksCount === 0) {
  72821. if (this.onFinish) {
  72822. this.onFinish(this.tasks);
  72823. }
  72824. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72825. return this;
  72826. }
  72827. if (this.useDefaultLoadingScreen) {
  72828. this._scene.getEngine().displayLoadingUI();
  72829. }
  72830. for (var index = 0; index < this.tasks.length; index++) {
  72831. var task = this.tasks[index];
  72832. this._runTask(task);
  72833. }
  72834. return this;
  72835. };
  72836. return AssetsManager;
  72837. }());
  72838. BABYLON.AssetsManager = AssetsManager;
  72839. })(BABYLON || (BABYLON = {}));
  72840. //# sourceMappingURL=babylon.assetsManager.js.map
  72841. var BABYLON;
  72842. (function (BABYLON) {
  72843. var serializedGeometries = [];
  72844. var serializeGeometry = function (geometry, serializationGeometries) {
  72845. if (serializedGeometries[geometry.id]) {
  72846. return;
  72847. }
  72848. if (geometry.doNotSerialize) {
  72849. return;
  72850. }
  72851. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  72852. serializationGeometries.boxes.push(geometry.serialize());
  72853. }
  72854. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  72855. serializationGeometries.spheres.push(geometry.serialize());
  72856. }
  72857. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  72858. serializationGeometries.cylinders.push(geometry.serialize());
  72859. }
  72860. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  72861. serializationGeometries.toruses.push(geometry.serialize());
  72862. }
  72863. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  72864. serializationGeometries.grounds.push(geometry.serialize());
  72865. }
  72866. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  72867. serializationGeometries.planes.push(geometry.serialize());
  72868. }
  72869. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  72870. serializationGeometries.torusKnots.push(geometry.serialize());
  72871. }
  72872. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  72873. throw new Error("Unknown primitive type");
  72874. }
  72875. else {
  72876. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  72877. }
  72878. serializedGeometries[geometry.id] = true;
  72879. };
  72880. var serializeMesh = function (mesh, serializationScene) {
  72881. var serializationObject = {};
  72882. // Geometry
  72883. var geometry = mesh._geometry;
  72884. if (geometry) {
  72885. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  72886. // 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
  72887. serializeGeometry(geometry, serializationScene.geometries);
  72888. }
  72889. }
  72890. // Custom
  72891. if (mesh.serialize) {
  72892. mesh.serialize(serializationObject);
  72893. }
  72894. return serializationObject;
  72895. };
  72896. var finalizeSingleMesh = function (mesh, serializationObject) {
  72897. //only works if the mesh is already loaded
  72898. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  72899. //serialize material
  72900. if (mesh.material) {
  72901. if (mesh.material instanceof BABYLON.StandardMaterial) {
  72902. serializationObject.materials = serializationObject.materials || [];
  72903. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72904. serializationObject.materials.push(mesh.material.serialize());
  72905. }
  72906. }
  72907. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  72908. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  72909. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72910. serializationObject.multiMaterials.push(mesh.material.serialize());
  72911. }
  72912. }
  72913. }
  72914. //serialize geometry
  72915. var geometry = mesh._geometry;
  72916. if (geometry) {
  72917. if (!serializationObject.geometries) {
  72918. serializationObject.geometries = {};
  72919. serializationObject.geometries.boxes = [];
  72920. serializationObject.geometries.spheres = [];
  72921. serializationObject.geometries.cylinders = [];
  72922. serializationObject.geometries.toruses = [];
  72923. serializationObject.geometries.grounds = [];
  72924. serializationObject.geometries.planes = [];
  72925. serializationObject.geometries.torusKnots = [];
  72926. serializationObject.geometries.vertexData = [];
  72927. }
  72928. serializeGeometry(geometry, serializationObject.geometries);
  72929. }
  72930. // Skeletons
  72931. if (mesh.skeleton) {
  72932. serializationObject.skeletons = serializationObject.skeletons || [];
  72933. serializationObject.skeletons.push(mesh.skeleton.serialize());
  72934. }
  72935. //serialize the actual mesh
  72936. serializationObject.meshes = serializationObject.meshes || [];
  72937. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  72938. }
  72939. };
  72940. var SceneSerializer = /** @class */ (function () {
  72941. function SceneSerializer() {
  72942. }
  72943. SceneSerializer.ClearCache = function () {
  72944. serializedGeometries = [];
  72945. };
  72946. SceneSerializer.Serialize = function (scene) {
  72947. var serializationObject = {};
  72948. SceneSerializer.ClearCache();
  72949. // Scene
  72950. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  72951. serializationObject.autoClear = scene.autoClear;
  72952. serializationObject.clearColor = scene.clearColor.asArray();
  72953. serializationObject.ambientColor = scene.ambientColor.asArray();
  72954. serializationObject.gravity = scene.gravity.asArray();
  72955. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  72956. serializationObject.workerCollisions = scene.workerCollisions;
  72957. // Fog
  72958. if (scene.fogMode && scene.fogMode !== 0) {
  72959. serializationObject.fogMode = scene.fogMode;
  72960. serializationObject.fogColor = scene.fogColor.asArray();
  72961. serializationObject.fogStart = scene.fogStart;
  72962. serializationObject.fogEnd = scene.fogEnd;
  72963. serializationObject.fogDensity = scene.fogDensity;
  72964. }
  72965. //Physics
  72966. if (scene.isPhysicsEnabled()) {
  72967. var physicEngine = scene.getPhysicsEngine();
  72968. if (physicEngine) {
  72969. serializationObject.physicsEnabled = true;
  72970. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  72971. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  72972. }
  72973. }
  72974. // Metadata
  72975. if (scene.metadata) {
  72976. serializationObject.metadata = scene.metadata;
  72977. }
  72978. // Morph targets
  72979. serializationObject.morphTargetManagers = [];
  72980. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  72981. var abstractMesh = _a[_i];
  72982. var manager = abstractMesh.morphTargetManager;
  72983. if (manager) {
  72984. serializationObject.morphTargetManagers.push(manager.serialize());
  72985. }
  72986. }
  72987. // Lights
  72988. serializationObject.lights = [];
  72989. var index;
  72990. var light;
  72991. for (index = 0; index < scene.lights.length; index++) {
  72992. light = scene.lights[index];
  72993. if (!light.doNotSerialize) {
  72994. serializationObject.lights.push(light.serialize());
  72995. }
  72996. }
  72997. // Cameras
  72998. serializationObject.cameras = [];
  72999. for (index = 0; index < scene.cameras.length; index++) {
  73000. var camera = scene.cameras[index];
  73001. if (!camera.doNotSerialize) {
  73002. serializationObject.cameras.push(camera.serialize());
  73003. }
  73004. }
  73005. if (scene.activeCamera) {
  73006. serializationObject.activeCameraID = scene.activeCamera.id;
  73007. }
  73008. // Animations
  73009. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  73010. // Materials
  73011. serializationObject.materials = [];
  73012. serializationObject.multiMaterials = [];
  73013. var material;
  73014. for (index = 0; index < scene.materials.length; index++) {
  73015. material = scene.materials[index];
  73016. if (!material.doNotSerialize) {
  73017. serializationObject.materials.push(material.serialize());
  73018. }
  73019. }
  73020. // MultiMaterials
  73021. serializationObject.multiMaterials = [];
  73022. for (index = 0; index < scene.multiMaterials.length; index++) {
  73023. var multiMaterial = scene.multiMaterials[index];
  73024. serializationObject.multiMaterials.push(multiMaterial.serialize());
  73025. }
  73026. // Skeletons
  73027. serializationObject.skeletons = [];
  73028. for (index = 0; index < scene.skeletons.length; index++) {
  73029. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  73030. }
  73031. // Geometries
  73032. serializationObject.geometries = {};
  73033. serializationObject.geometries.boxes = [];
  73034. serializationObject.geometries.spheres = [];
  73035. serializationObject.geometries.cylinders = [];
  73036. serializationObject.geometries.toruses = [];
  73037. serializationObject.geometries.grounds = [];
  73038. serializationObject.geometries.planes = [];
  73039. serializationObject.geometries.torusKnots = [];
  73040. serializationObject.geometries.vertexData = [];
  73041. serializedGeometries = [];
  73042. var geometries = scene.getGeometries();
  73043. for (index = 0; index < geometries.length; index++) {
  73044. var geometry = geometries[index];
  73045. if (geometry.isReady()) {
  73046. serializeGeometry(geometry, serializationObject.geometries);
  73047. }
  73048. }
  73049. // Meshes
  73050. serializationObject.meshes = [];
  73051. for (index = 0; index < scene.meshes.length; index++) {
  73052. var abstractMesh = scene.meshes[index];
  73053. if (abstractMesh instanceof BABYLON.Mesh) {
  73054. var mesh = abstractMesh;
  73055. if (!mesh.doNotSerialize) {
  73056. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  73057. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73058. }
  73059. }
  73060. }
  73061. }
  73062. // Particles Systems
  73063. serializationObject.particleSystems = [];
  73064. for (index = 0; index < scene.particleSystems.length; index++) {
  73065. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  73066. }
  73067. // Lens flares
  73068. serializationObject.lensFlareSystems = [];
  73069. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  73070. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  73071. }
  73072. // Shadows
  73073. serializationObject.shadowGenerators = [];
  73074. for (index = 0; index < scene.lights.length; index++) {
  73075. light = scene.lights[index];
  73076. var shadowGenerator = light.getShadowGenerator();
  73077. if (shadowGenerator) {
  73078. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73079. }
  73080. }
  73081. // Action Manager
  73082. if (scene.actionManager) {
  73083. serializationObject.actions = scene.actionManager.serialize("scene");
  73084. }
  73085. // Audio
  73086. serializationObject.sounds = [];
  73087. for (index = 0; index < scene.soundTracks.length; index++) {
  73088. var soundtrack = scene.soundTracks[index];
  73089. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  73090. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  73091. }
  73092. }
  73093. return serializationObject;
  73094. };
  73095. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  73096. if (withParents === void 0) { withParents = false; }
  73097. if (withChildren === void 0) { withChildren = false; }
  73098. var serializationObject = {};
  73099. SceneSerializer.ClearCache();
  73100. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  73101. if (withParents || withChildren) {
  73102. //deliberate for loop! not for each, appended should be processed as well.
  73103. for (var i = 0; i < toSerialize.length; ++i) {
  73104. if (withChildren) {
  73105. toSerialize[i].getDescendants().forEach(function (node) {
  73106. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  73107. toSerialize.push(node);
  73108. }
  73109. });
  73110. }
  73111. //make sure the array doesn't contain the object already
  73112. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  73113. toSerialize.push(toSerialize[i].parent);
  73114. }
  73115. }
  73116. }
  73117. toSerialize.forEach(function (mesh) {
  73118. finalizeSingleMesh(mesh, serializationObject);
  73119. });
  73120. return serializationObject;
  73121. };
  73122. return SceneSerializer;
  73123. }());
  73124. BABYLON.SceneSerializer = SceneSerializer;
  73125. })(BABYLON || (BABYLON = {}));
  73126. //# sourceMappingURL=babylon.sceneSerializer.js.map
  73127. var BABYLON;
  73128. (function (BABYLON) {
  73129. var ReflectionProbe = /** @class */ (function () {
  73130. function ReflectionProbe(name, size, scene, generateMipMaps) {
  73131. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73132. var _this = this;
  73133. this.name = name;
  73134. this._viewMatrix = BABYLON.Matrix.Identity();
  73135. this._target = BABYLON.Vector3.Zero();
  73136. this._add = BABYLON.Vector3.Zero();
  73137. this.invertYAxis = false;
  73138. this.position = BABYLON.Vector3.Zero();
  73139. this._scene = scene;
  73140. this._scene.reflectionProbes.push(this);
  73141. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  73142. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  73143. switch (faceIndex) {
  73144. case 0:
  73145. _this._add.copyFromFloats(1, 0, 0);
  73146. break;
  73147. case 1:
  73148. _this._add.copyFromFloats(-1, 0, 0);
  73149. break;
  73150. case 2:
  73151. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  73152. break;
  73153. case 3:
  73154. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  73155. break;
  73156. case 4:
  73157. _this._add.copyFromFloats(0, 0, 1);
  73158. break;
  73159. case 5:
  73160. _this._add.copyFromFloats(0, 0, -1);
  73161. break;
  73162. }
  73163. if (_this._attachedMesh) {
  73164. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  73165. }
  73166. _this.position.addToRef(_this._add, _this._target);
  73167. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  73168. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  73169. scene._forcedViewPosition = _this.position;
  73170. });
  73171. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  73172. scene._forcedViewPosition = null;
  73173. scene.updateTransformMatrix(true);
  73174. });
  73175. if (scene.activeCamera) {
  73176. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73177. }
  73178. }
  73179. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  73180. get: function () {
  73181. return this._renderTargetTexture.samples;
  73182. },
  73183. set: function (value) {
  73184. this._renderTargetTexture.samples = value;
  73185. },
  73186. enumerable: true,
  73187. configurable: true
  73188. });
  73189. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  73190. get: function () {
  73191. return this._renderTargetTexture.refreshRate;
  73192. },
  73193. set: function (value) {
  73194. this._renderTargetTexture.refreshRate = value;
  73195. },
  73196. enumerable: true,
  73197. configurable: true
  73198. });
  73199. ReflectionProbe.prototype.getScene = function () {
  73200. return this._scene;
  73201. };
  73202. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  73203. get: function () {
  73204. return this._renderTargetTexture;
  73205. },
  73206. enumerable: true,
  73207. configurable: true
  73208. });
  73209. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  73210. get: function () {
  73211. return this._renderTargetTexture.renderList;
  73212. },
  73213. enumerable: true,
  73214. configurable: true
  73215. });
  73216. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  73217. this._attachedMesh = mesh;
  73218. };
  73219. /**
  73220. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73221. *
  73222. * @param renderingGroupId The rendering group id corresponding to its index
  73223. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73224. */
  73225. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73226. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73227. };
  73228. ReflectionProbe.prototype.dispose = function () {
  73229. var index = this._scene.reflectionProbes.indexOf(this);
  73230. if (index !== -1) {
  73231. // Remove from the scene if found
  73232. this._scene.reflectionProbes.splice(index, 1);
  73233. }
  73234. if (this._renderTargetTexture) {
  73235. this._renderTargetTexture.dispose();
  73236. this._renderTargetTexture = null;
  73237. }
  73238. };
  73239. return ReflectionProbe;
  73240. }());
  73241. BABYLON.ReflectionProbe = ReflectionProbe;
  73242. })(BABYLON || (BABYLON = {}));
  73243. //# sourceMappingURL=babylon.reflectionProbe.js.map
  73244. var BABYLON;
  73245. (function (BABYLON) {
  73246. var Layer = /** @class */ (function () {
  73247. function Layer(name, imgUrl, scene, isBackground, color) {
  73248. this.name = name;
  73249. this.scale = new BABYLON.Vector2(1, 1);
  73250. this.offset = new BABYLON.Vector2(0, 0);
  73251. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  73252. this.layerMask = 0x0FFFFFFF;
  73253. this._vertexBuffers = {};
  73254. // Events
  73255. /**
  73256. * An event triggered when the layer is disposed.
  73257. * @type {BABYLON.Observable}
  73258. */
  73259. this.onDisposeObservable = new BABYLON.Observable();
  73260. /**
  73261. * An event triggered before rendering the scene
  73262. * @type {BABYLON.Observable}
  73263. */
  73264. this.onBeforeRenderObservable = new BABYLON.Observable();
  73265. /**
  73266. * An event triggered after rendering the scene
  73267. * @type {BABYLON.Observable}
  73268. */
  73269. this.onAfterRenderObservable = new BABYLON.Observable();
  73270. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  73271. this.isBackground = isBackground === undefined ? true : isBackground;
  73272. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  73273. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  73274. this._scene.layers.push(this);
  73275. var engine = this._scene.getEngine();
  73276. // VBO
  73277. var vertices = [];
  73278. vertices.push(1, 1);
  73279. vertices.push(-1, 1);
  73280. vertices.push(-1, -1);
  73281. vertices.push(1, -1);
  73282. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73283. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  73284. this._createIndexBuffer();
  73285. // Effects
  73286. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  73287. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  73288. }
  73289. Object.defineProperty(Layer.prototype, "onDispose", {
  73290. set: function (callback) {
  73291. if (this._onDisposeObserver) {
  73292. this.onDisposeObservable.remove(this._onDisposeObserver);
  73293. }
  73294. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  73295. },
  73296. enumerable: true,
  73297. configurable: true
  73298. });
  73299. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  73300. set: function (callback) {
  73301. if (this._onBeforeRenderObserver) {
  73302. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73303. }
  73304. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73305. },
  73306. enumerable: true,
  73307. configurable: true
  73308. });
  73309. Object.defineProperty(Layer.prototype, "onAfterRender", {
  73310. set: function (callback) {
  73311. if (this._onAfterRenderObserver) {
  73312. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73313. }
  73314. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73315. },
  73316. enumerable: true,
  73317. configurable: true
  73318. });
  73319. Layer.prototype._createIndexBuffer = function () {
  73320. var engine = this._scene.getEngine();
  73321. // Indices
  73322. var indices = [];
  73323. indices.push(0);
  73324. indices.push(1);
  73325. indices.push(2);
  73326. indices.push(0);
  73327. indices.push(2);
  73328. indices.push(3);
  73329. this._indexBuffer = engine.createIndexBuffer(indices);
  73330. };
  73331. Layer.prototype._rebuild = function () {
  73332. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73333. if (vb) {
  73334. vb._rebuild();
  73335. }
  73336. this._createIndexBuffer();
  73337. };
  73338. Layer.prototype.render = function () {
  73339. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  73340. // Check
  73341. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  73342. return;
  73343. var engine = this._scene.getEngine();
  73344. this.onBeforeRenderObservable.notifyObservers(this);
  73345. // Render
  73346. engine.enableEffect(currentEffect);
  73347. engine.setState(false);
  73348. // Texture
  73349. currentEffect.setTexture("textureSampler", this.texture);
  73350. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  73351. // Color
  73352. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  73353. // Scale / offset
  73354. currentEffect.setVector2("offset", this.offset);
  73355. currentEffect.setVector2("scale", this.scale);
  73356. // VBOs
  73357. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73358. // Draw order
  73359. if (!this.alphaTest) {
  73360. engine.setAlphaMode(this.alphaBlendingMode);
  73361. engine.draw(true, 0, 6);
  73362. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73363. }
  73364. else {
  73365. engine.draw(true, 0, 6);
  73366. }
  73367. this.onAfterRenderObservable.notifyObservers(this);
  73368. };
  73369. Layer.prototype.dispose = function () {
  73370. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73371. if (vertexBuffer) {
  73372. vertexBuffer.dispose();
  73373. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73374. }
  73375. if (this._indexBuffer) {
  73376. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73377. this._indexBuffer = null;
  73378. }
  73379. if (this.texture) {
  73380. this.texture.dispose();
  73381. this.texture = null;
  73382. }
  73383. // Remove from scene
  73384. var index = this._scene.layers.indexOf(this);
  73385. this._scene.layers.splice(index, 1);
  73386. // Callback
  73387. this.onDisposeObservable.notifyObservers(this);
  73388. this.onDisposeObservable.clear();
  73389. this.onAfterRenderObservable.clear();
  73390. this.onBeforeRenderObservable.clear();
  73391. };
  73392. return Layer;
  73393. }());
  73394. BABYLON.Layer = Layer;
  73395. })(BABYLON || (BABYLON = {}));
  73396. //# sourceMappingURL=babylon.layer.js.map
  73397. var BABYLON;
  73398. (function (BABYLON) {
  73399. var TextureTools = /** @class */ (function () {
  73400. function TextureTools() {
  73401. }
  73402. /**
  73403. * Uses the GPU to create a copy texture rescaled at a given size
  73404. * @param texture Texture to copy from
  73405. * @param width Desired width
  73406. * @param height Desired height
  73407. * @return Generated texture
  73408. */
  73409. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  73410. if (useBilinearMode === void 0) { useBilinearMode = true; }
  73411. var scene = texture.getScene();
  73412. var engine = scene.getEngine();
  73413. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  73414. rtt.wrapU = texture.wrapU;
  73415. rtt.wrapV = texture.wrapV;
  73416. rtt.uOffset = texture.uOffset;
  73417. rtt.vOffset = texture.vOffset;
  73418. rtt.uScale = texture.uScale;
  73419. rtt.vScale = texture.vScale;
  73420. rtt.uAng = texture.uAng;
  73421. rtt.vAng = texture.vAng;
  73422. rtt.wAng = texture.wAng;
  73423. rtt.coordinatesIndex = texture.coordinatesIndex;
  73424. rtt.level = texture.level;
  73425. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  73426. rtt._texture.isReady = false;
  73427. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73428. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73429. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73430. passPostProcess.getEffect().executeWhenCompiled(function () {
  73431. passPostProcess.onApply = function (effect) {
  73432. effect.setTexture("textureSampler", texture);
  73433. };
  73434. var internalTexture = rtt.getInternalTexture();
  73435. if (internalTexture) {
  73436. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  73437. engine.unBindFramebuffer(internalTexture);
  73438. rtt.disposeFramebufferObjects();
  73439. passPostProcess.dispose();
  73440. internalTexture.isReady = true;
  73441. }
  73442. });
  73443. return rtt;
  73444. };
  73445. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  73446. if (!scene._environmentBRDFTexture) {
  73447. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73448. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73449. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73450. scene._environmentBRDFTexture = texture;
  73451. }
  73452. return scene._environmentBRDFTexture;
  73453. };
  73454. 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=";
  73455. return TextureTools;
  73456. }());
  73457. BABYLON.TextureTools = TextureTools;
  73458. })(BABYLON || (BABYLON = {}));
  73459. //# sourceMappingURL=babylon.textureTools.js.map
  73460. var BABYLON;
  73461. (function (BABYLON) {
  73462. var FramingBehavior = /** @class */ (function () {
  73463. function FramingBehavior() {
  73464. this._mode = FramingBehavior.FitFrustumSidesMode;
  73465. this._radiusScale = 1.0;
  73466. this._positionScale = 0.5;
  73467. this._defaultElevation = 0.3;
  73468. this._elevationReturnTime = 1500;
  73469. this._elevationReturnWaitTime = 1000;
  73470. this._zoomStopsAnimation = false;
  73471. this._framingTime = 1500;
  73472. this._isPointerDown = false;
  73473. this._lastInteractionTime = -Infinity;
  73474. // Framing control
  73475. this._animatables = new Array();
  73476. this._betaIsAnimating = false;
  73477. }
  73478. Object.defineProperty(FramingBehavior.prototype, "name", {
  73479. get: function () {
  73480. return "Framing";
  73481. },
  73482. enumerable: true,
  73483. configurable: true
  73484. });
  73485. Object.defineProperty(FramingBehavior.prototype, "mode", {
  73486. /**
  73487. * Gets current mode used by the behavior.
  73488. */
  73489. get: function () {
  73490. return this._mode;
  73491. },
  73492. /**
  73493. * Sets the current mode used by the behavior
  73494. */
  73495. set: function (mode) {
  73496. this._mode = mode;
  73497. },
  73498. enumerable: true,
  73499. configurable: true
  73500. });
  73501. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  73502. /**
  73503. * Gets the scale applied to the radius
  73504. */
  73505. get: function () {
  73506. return this._radiusScale;
  73507. },
  73508. /**
  73509. * Sets the scale applied to the radius (1 by default)
  73510. */
  73511. set: function (radius) {
  73512. this._radiusScale = radius;
  73513. },
  73514. enumerable: true,
  73515. configurable: true
  73516. });
  73517. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  73518. /**
  73519. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73520. */
  73521. get: function () {
  73522. return this._positionScale;
  73523. },
  73524. /**
  73525. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73526. */
  73527. set: function (scale) {
  73528. this._positionScale = scale;
  73529. },
  73530. enumerable: true,
  73531. configurable: true
  73532. });
  73533. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  73534. /**
  73535. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73536. * behaviour is triggered, in radians.
  73537. */
  73538. get: function () {
  73539. return this._defaultElevation;
  73540. },
  73541. /**
  73542. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73543. * behaviour is triggered, in radians.
  73544. */
  73545. set: function (elevation) {
  73546. this._defaultElevation = elevation;
  73547. },
  73548. enumerable: true,
  73549. configurable: true
  73550. });
  73551. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  73552. /**
  73553. * Gets the time (in milliseconds) taken to return to the default beta position.
  73554. * Negative value indicates camera should not return to default.
  73555. */
  73556. get: function () {
  73557. return this._elevationReturnTime;
  73558. },
  73559. /**
  73560. * Sets the time (in milliseconds) taken to return to the default beta position.
  73561. * Negative value indicates camera should not return to default.
  73562. */
  73563. set: function (speed) {
  73564. this._elevationReturnTime = speed;
  73565. },
  73566. enumerable: true,
  73567. configurable: true
  73568. });
  73569. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  73570. /**
  73571. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73572. */
  73573. get: function () {
  73574. return this._elevationReturnWaitTime;
  73575. },
  73576. /**
  73577. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73578. */
  73579. set: function (time) {
  73580. this._elevationReturnWaitTime = time;
  73581. },
  73582. enumerable: true,
  73583. configurable: true
  73584. });
  73585. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  73586. /**
  73587. * Gets the flag that indicates if user zooming should stop animation.
  73588. */
  73589. get: function () {
  73590. return this._zoomStopsAnimation;
  73591. },
  73592. /**
  73593. * Sets the flag that indicates if user zooming should stop animation.
  73594. */
  73595. set: function (flag) {
  73596. this._zoomStopsAnimation = flag;
  73597. },
  73598. enumerable: true,
  73599. configurable: true
  73600. });
  73601. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  73602. /**
  73603. * Gets the transition time when framing the mesh, in milliseconds
  73604. */
  73605. get: function () {
  73606. return this._framingTime;
  73607. },
  73608. /**
  73609. * Sets the transition time when framing the mesh, in milliseconds
  73610. */
  73611. set: function (time) {
  73612. this._framingTime = time;
  73613. },
  73614. enumerable: true,
  73615. configurable: true
  73616. });
  73617. FramingBehavior.prototype.attach = function (camera) {
  73618. var _this = this;
  73619. this._attachedCamera = camera;
  73620. var scene = this._attachedCamera.getScene();
  73621. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  73622. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73623. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73624. _this._isPointerDown = true;
  73625. return;
  73626. }
  73627. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  73628. _this._isPointerDown = false;
  73629. }
  73630. });
  73631. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73632. if (mesh) {
  73633. _this.zoomOnMesh(mesh);
  73634. }
  73635. });
  73636. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73637. // Stop the animation if there is user interaction and the animation should stop for this interaction
  73638. _this._applyUserInteraction();
  73639. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  73640. // back to the default position after a given timeout
  73641. _this._maintainCameraAboveGround();
  73642. });
  73643. };
  73644. FramingBehavior.prototype.detach = function () {
  73645. if (!this._attachedCamera) {
  73646. return;
  73647. }
  73648. var scene = this._attachedCamera.getScene();
  73649. if (this._onPrePointerObservableObserver) {
  73650. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  73651. }
  73652. if (this._onAfterCheckInputsObserver) {
  73653. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73654. }
  73655. if (this._onMeshTargetChangedObserver) {
  73656. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73657. }
  73658. this._attachedCamera = null;
  73659. };
  73660. /**
  73661. * Targets the given mesh and updates zoom level accordingly.
  73662. * @param mesh The mesh to target.
  73663. * @param radius Optional. If a cached radius position already exists, overrides default.
  73664. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73665. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73666. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73667. */
  73668. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  73669. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73670. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73671. mesh.computeWorldMatrix(true);
  73672. var boundingBox = mesh.getBoundingInfo().boundingBox;
  73673. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  73674. };
  73675. /**
  73676. * Targets the given mesh and updates zoom level accordingly.
  73677. * @param mesh The mesh to target.
  73678. * @param radius Optional. If a cached radius position already exists, overrides default.
  73679. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73680. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73681. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73682. */
  73683. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  73684. var _this = this;
  73685. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73686. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73687. var zoomTarget;
  73688. if (!this._attachedCamera) {
  73689. return;
  73690. }
  73691. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  73692. var bottom = minimumWorld.y;
  73693. var top = maximumWorld.y;
  73694. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  73695. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  73696. if (focusOnOriginXZ) {
  73697. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  73698. }
  73699. else {
  73700. var centerWorld = minimumWorld.add(radiusWorld);
  73701. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  73702. }
  73703. if (!this._vectorTransition) {
  73704. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  73705. }
  73706. this._betaIsAnimating = true;
  73707. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  73708. if (animatable) {
  73709. this._animatables.push(animatable);
  73710. }
  73711. // sets the radius and lower radius bounds
  73712. // Small delta ensures camera is not always at lower zoom limit.
  73713. var radius = 0;
  73714. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  73715. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73716. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  73717. radius = position;
  73718. }
  73719. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73720. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73721. if (this._attachedCamera.lowerRadiusLimit === null) {
  73722. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  73723. }
  73724. }
  73725. // Set sensibilities
  73726. var extend = maximumWorld.subtract(minimumWorld).length();
  73727. this._attachedCamera.panningSensibility = 5000 / extend;
  73728. this._attachedCamera.wheelPrecision = 100 / radius;
  73729. // transition to new radius
  73730. if (!this._radiusTransition) {
  73731. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73732. }
  73733. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  73734. if (onAnimationEnd) {
  73735. onAnimationEnd();
  73736. }
  73737. if (_this._attachedCamera) {
  73738. _this._attachedCamera.storeState();
  73739. }
  73740. });
  73741. if (animatable) {
  73742. this._animatables.push(animatable);
  73743. }
  73744. };
  73745. /**
  73746. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  73747. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  73748. * frustum width.
  73749. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  73750. * to fully enclose the mesh in the viewing frustum.
  73751. */
  73752. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  73753. var size = maximumWorld.subtract(minimumWorld);
  73754. var boxVectorGlobalDiagonal = size.length();
  73755. var frustumSlope = this._getFrustumSlope();
  73756. // Formula for setting distance
  73757. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  73758. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  73759. // Horizon distance
  73760. var radius = radiusWithoutFraming * this._radiusScale;
  73761. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  73762. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  73763. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  73764. var camera = this._attachedCamera;
  73765. if (!camera) {
  73766. return 0;
  73767. }
  73768. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73769. // Don't exceed the requested limit
  73770. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  73771. }
  73772. // Don't exceed the upper radius limit
  73773. if (camera.upperRadiusLimit) {
  73774. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  73775. }
  73776. return distance;
  73777. };
  73778. /**
  73779. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  73780. * is automatically returned to its default position (expected to be above ground plane).
  73781. */
  73782. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  73783. var _this = this;
  73784. if (this._elevationReturnTime < 0) {
  73785. return;
  73786. }
  73787. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  73788. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  73789. var limitBeta = Math.PI * 0.5;
  73790. // Bring the camera back up if below the ground plane
  73791. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  73792. this._betaIsAnimating = true;
  73793. //Transition to new position
  73794. this.stopAllAnimations();
  73795. if (!this._betaTransition) {
  73796. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73797. }
  73798. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  73799. _this._clearAnimationLocks();
  73800. _this.stopAllAnimations();
  73801. });
  73802. if (animatabe) {
  73803. this._animatables.push(animatabe);
  73804. }
  73805. }
  73806. };
  73807. /**
  73808. * Returns the frustum slope based on the canvas ratio and camera FOV
  73809. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  73810. */
  73811. FramingBehavior.prototype._getFrustumSlope = function () {
  73812. // Calculate the viewport ratio
  73813. // Aspect Ratio is Height/Width.
  73814. var camera = this._attachedCamera;
  73815. if (!camera) {
  73816. return BABYLON.Vector2.Zero();
  73817. }
  73818. var engine = camera.getScene().getEngine();
  73819. var aspectRatio = engine.getAspectRatio(camera);
  73820. // Camera FOV is the vertical field of view (top-bottom) in radians.
  73821. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  73822. var frustumSlopeY = Math.tan(camera.fov / 2);
  73823. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  73824. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  73825. // along the forward vector.
  73826. var frustumSlopeX = frustumSlopeY * aspectRatio;
  73827. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  73828. };
  73829. /**
  73830. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  73831. */
  73832. FramingBehavior.prototype._clearAnimationLocks = function () {
  73833. this._betaIsAnimating = false;
  73834. };
  73835. /**
  73836. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  73837. */
  73838. FramingBehavior.prototype._applyUserInteraction = function () {
  73839. if (this.isUserIsMoving) {
  73840. this._lastInteractionTime = BABYLON.Tools.Now;
  73841. this.stopAllAnimations();
  73842. this._clearAnimationLocks();
  73843. }
  73844. };
  73845. /**
  73846. * Stops and removes all animations that have been applied to the camera
  73847. */
  73848. FramingBehavior.prototype.stopAllAnimations = function () {
  73849. if (this._attachedCamera) {
  73850. this._attachedCamera.animations = [];
  73851. }
  73852. while (this._animatables.length) {
  73853. if (this._animatables[0]) {
  73854. this._animatables[0].onAnimationEnd = null;
  73855. this._animatables[0].stop();
  73856. }
  73857. this._animatables.shift();
  73858. }
  73859. };
  73860. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  73861. /**
  73862. * Gets a value indicating if the user is moving the camera
  73863. */
  73864. get: function () {
  73865. if (!this._attachedCamera) {
  73866. return false;
  73867. }
  73868. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  73869. this._attachedCamera.inertialBetaOffset !== 0 ||
  73870. this._attachedCamera.inertialRadiusOffset !== 0 ||
  73871. this._attachedCamera.inertialPanningX !== 0 ||
  73872. this._attachedCamera.inertialPanningY !== 0 ||
  73873. this._isPointerDown;
  73874. },
  73875. enumerable: true,
  73876. configurable: true
  73877. });
  73878. /**
  73879. * The easing function used by animations
  73880. */
  73881. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  73882. /**
  73883. * The easing mode used by animations
  73884. */
  73885. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  73886. // Statics
  73887. /**
  73888. * The camera can move all the way towards the mesh.
  73889. */
  73890. FramingBehavior.IgnoreBoundsSizeMode = 0;
  73891. /**
  73892. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  73893. */
  73894. FramingBehavior.FitFrustumSidesMode = 1;
  73895. return FramingBehavior;
  73896. }());
  73897. BABYLON.FramingBehavior = FramingBehavior;
  73898. })(BABYLON || (BABYLON = {}));
  73899. //# sourceMappingURL=babylon.framingBehavior.js.map
  73900. var BABYLON;
  73901. (function (BABYLON) {
  73902. /**
  73903. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  73904. */
  73905. var BouncingBehavior = /** @class */ (function () {
  73906. function BouncingBehavior() {
  73907. /**
  73908. * The duration of the animation, in milliseconds
  73909. */
  73910. this.transitionDuration = 450;
  73911. /**
  73912. * Length of the distance animated by the transition when lower radius is reached
  73913. */
  73914. this.lowerRadiusTransitionRange = 2;
  73915. /**
  73916. * Length of the distance animated by the transition when upper radius is reached
  73917. */
  73918. this.upperRadiusTransitionRange = -2;
  73919. this._autoTransitionRange = false;
  73920. // Animations
  73921. this._radiusIsAnimating = false;
  73922. this._radiusBounceTransition = null;
  73923. this._animatables = new Array();
  73924. }
  73925. Object.defineProperty(BouncingBehavior.prototype, "name", {
  73926. get: function () {
  73927. return "Bouncing";
  73928. },
  73929. enumerable: true,
  73930. configurable: true
  73931. });
  73932. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  73933. /**
  73934. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73935. */
  73936. get: function () {
  73937. return this._autoTransitionRange;
  73938. },
  73939. /**
  73940. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73941. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  73942. */
  73943. set: function (value) {
  73944. var _this = this;
  73945. if (this._autoTransitionRange === value) {
  73946. return;
  73947. }
  73948. this._autoTransitionRange = value;
  73949. var camera = this._attachedCamera;
  73950. if (!camera) {
  73951. return;
  73952. }
  73953. if (value) {
  73954. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73955. if (!mesh) {
  73956. return;
  73957. }
  73958. mesh.computeWorldMatrix(true);
  73959. var diagonal = mesh.getBoundingInfo().diagonalLength;
  73960. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  73961. _this.upperRadiusTransitionRange = diagonal * 0.05;
  73962. });
  73963. }
  73964. else if (this._onMeshTargetChangedObserver) {
  73965. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73966. }
  73967. },
  73968. enumerable: true,
  73969. configurable: true
  73970. });
  73971. BouncingBehavior.prototype.attach = function (camera) {
  73972. var _this = this;
  73973. this._attachedCamera = camera;
  73974. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73975. if (!_this._attachedCamera) {
  73976. return;
  73977. }
  73978. // Add the bounce animation to the lower radius limit
  73979. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  73980. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  73981. }
  73982. // Add the bounce animation to the upper radius limit
  73983. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  73984. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  73985. }
  73986. });
  73987. };
  73988. BouncingBehavior.prototype.detach = function () {
  73989. if (!this._attachedCamera) {
  73990. return;
  73991. }
  73992. if (this._onAfterCheckInputsObserver) {
  73993. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73994. }
  73995. if (this._onMeshTargetChangedObserver) {
  73996. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73997. }
  73998. this._attachedCamera = null;
  73999. };
  74000. /**
  74001. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  74002. * @param radiusLimit The limit to check against.
  74003. * @return Bool to indicate if at limit.
  74004. */
  74005. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  74006. if (!this._attachedCamera) {
  74007. return false;
  74008. }
  74009. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  74010. return true;
  74011. }
  74012. return false;
  74013. };
  74014. /**
  74015. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  74016. * @param radiusDelta The delta by which to animate to. Can be negative.
  74017. */
  74018. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  74019. var _this = this;
  74020. if (!this._attachedCamera) {
  74021. return;
  74022. }
  74023. if (!this._radiusBounceTransition) {
  74024. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  74025. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  74026. }
  74027. // Prevent zoom until bounce has completed
  74028. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  74029. this._attachedCamera.wheelPrecision = Infinity;
  74030. this._attachedCamera.inertialRadiusOffset = 0;
  74031. // Animate to the radius limit
  74032. this.stopAllAnimations();
  74033. this._radiusIsAnimating = true;
  74034. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  74035. if (animatable) {
  74036. this._animatables.push(animatable);
  74037. }
  74038. };
  74039. /**
  74040. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  74041. */
  74042. BouncingBehavior.prototype._clearAnimationLocks = function () {
  74043. this._radiusIsAnimating = false;
  74044. if (this._attachedCamera) {
  74045. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  74046. }
  74047. };
  74048. /**
  74049. * Stops and removes all animations that have been applied to the camera
  74050. */
  74051. BouncingBehavior.prototype.stopAllAnimations = function () {
  74052. if (this._attachedCamera) {
  74053. this._attachedCamera.animations = [];
  74054. }
  74055. while (this._animatables.length) {
  74056. this._animatables[0].onAnimationEnd = null;
  74057. this._animatables[0].stop();
  74058. this._animatables.shift();
  74059. }
  74060. };
  74061. /**
  74062. * The easing function used by animations
  74063. */
  74064. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  74065. /**
  74066. * The easing mode used by animations
  74067. */
  74068. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  74069. return BouncingBehavior;
  74070. }());
  74071. BABYLON.BouncingBehavior = BouncingBehavior;
  74072. })(BABYLON || (BABYLON = {}));
  74073. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  74074. var BABYLON;
  74075. (function (BABYLON) {
  74076. var AutoRotationBehavior = /** @class */ (function () {
  74077. function AutoRotationBehavior() {
  74078. this._zoomStopsAnimation = false;
  74079. this._idleRotationSpeed = 0.05;
  74080. this._idleRotationWaitTime = 2000;
  74081. this._idleRotationSpinupTime = 2000;
  74082. this._isPointerDown = false;
  74083. this._lastFrameTime = null;
  74084. this._lastInteractionTime = -Infinity;
  74085. this._cameraRotationSpeed = 0;
  74086. this._lastFrameRadius = 0;
  74087. }
  74088. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  74089. get: function () {
  74090. return "AutoRotation";
  74091. },
  74092. enumerable: true,
  74093. configurable: true
  74094. });
  74095. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  74096. /**
  74097. * Gets the flag that indicates if user zooming should stop animation.
  74098. */
  74099. get: function () {
  74100. return this._zoomStopsAnimation;
  74101. },
  74102. /**
  74103. * Sets the flag that indicates if user zooming should stop animation.
  74104. */
  74105. set: function (flag) {
  74106. this._zoomStopsAnimation = flag;
  74107. },
  74108. enumerable: true,
  74109. configurable: true
  74110. });
  74111. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  74112. /**
  74113. * Gets the default speed at which the camera rotates around the model.
  74114. */
  74115. get: function () {
  74116. return this._idleRotationSpeed;
  74117. },
  74118. /**
  74119. * Sets the default speed at which the camera rotates around the model.
  74120. */
  74121. set: function (speed) {
  74122. this._idleRotationSpeed = speed;
  74123. },
  74124. enumerable: true,
  74125. configurable: true
  74126. });
  74127. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  74128. /**
  74129. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  74130. */
  74131. get: function () {
  74132. return this._idleRotationWaitTime;
  74133. },
  74134. /**
  74135. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  74136. */
  74137. set: function (time) {
  74138. this._idleRotationWaitTime = time;
  74139. },
  74140. enumerable: true,
  74141. configurable: true
  74142. });
  74143. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  74144. /**
  74145. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74146. */
  74147. get: function () {
  74148. return this._idleRotationSpinupTime;
  74149. },
  74150. /**
  74151. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74152. */
  74153. set: function (time) {
  74154. this._idleRotationSpinupTime = time;
  74155. },
  74156. enumerable: true,
  74157. configurable: true
  74158. });
  74159. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  74160. /**
  74161. * Gets a value indicating if the camera is currently rotating because of this behavior
  74162. */
  74163. get: function () {
  74164. return Math.abs(this._cameraRotationSpeed) > 0;
  74165. },
  74166. enumerable: true,
  74167. configurable: true
  74168. });
  74169. AutoRotationBehavior.prototype.attach = function (camera) {
  74170. var _this = this;
  74171. this._attachedCamera = camera;
  74172. var scene = this._attachedCamera.getScene();
  74173. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  74174. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74175. _this._isPointerDown = true;
  74176. return;
  74177. }
  74178. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74179. _this._isPointerDown = false;
  74180. }
  74181. });
  74182. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74183. var now = BABYLON.Tools.Now;
  74184. var dt = 0;
  74185. if (_this._lastFrameTime != null) {
  74186. dt = now - _this._lastFrameTime;
  74187. }
  74188. _this._lastFrameTime = now;
  74189. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74190. _this._applyUserInteraction();
  74191. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  74192. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  74193. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  74194. // Step camera rotation by rotation speed
  74195. if (_this._attachedCamera) {
  74196. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  74197. }
  74198. });
  74199. };
  74200. AutoRotationBehavior.prototype.detach = function () {
  74201. if (!this._attachedCamera) {
  74202. return;
  74203. }
  74204. var scene = this._attachedCamera.getScene();
  74205. if (this._onPrePointerObservableObserver) {
  74206. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74207. }
  74208. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74209. this._attachedCamera = null;
  74210. };
  74211. /**
  74212. * Returns true if user is scrolling.
  74213. * @return true if user is scrolling.
  74214. */
  74215. AutoRotationBehavior.prototype._userIsZooming = function () {
  74216. if (!this._attachedCamera) {
  74217. return false;
  74218. }
  74219. return this._attachedCamera.inertialRadiusOffset !== 0;
  74220. };
  74221. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  74222. if (!this._attachedCamera) {
  74223. return false;
  74224. }
  74225. var zoomHasHitLimit = false;
  74226. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  74227. zoomHasHitLimit = true;
  74228. }
  74229. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  74230. this._lastFrameRadius = this._attachedCamera.radius;
  74231. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  74232. };
  74233. /**
  74234. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74235. */
  74236. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  74237. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  74238. this._lastInteractionTime = BABYLON.Tools.Now;
  74239. }
  74240. };
  74241. // Tools
  74242. AutoRotationBehavior.prototype._userIsMoving = function () {
  74243. if (!this._attachedCamera) {
  74244. return false;
  74245. }
  74246. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74247. this._attachedCamera.inertialBetaOffset !== 0 ||
  74248. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74249. this._attachedCamera.inertialPanningX !== 0 ||
  74250. this._attachedCamera.inertialPanningY !== 0 ||
  74251. this._isPointerDown;
  74252. };
  74253. return AutoRotationBehavior;
  74254. }());
  74255. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  74256. })(BABYLON || (BABYLON = {}));
  74257. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  74258. var BABYLON;
  74259. (function (BABYLON) {
  74260. /**
  74261. * This class can be used to get instrumentation data from a Babylon engine
  74262. */
  74263. var EngineInstrumentation = /** @class */ (function () {
  74264. function EngineInstrumentation(engine) {
  74265. this.engine = engine;
  74266. this._captureGPUFrameTime = false;
  74267. this._gpuFrameTime = new BABYLON.PerfCounter();
  74268. this._captureShaderCompilationTime = false;
  74269. this._shaderCompilationTime = new BABYLON.PerfCounter();
  74270. // Observers
  74271. this._onBeginFrameObserver = null;
  74272. this._onEndFrameObserver = null;
  74273. this._onBeforeShaderCompilationObserver = null;
  74274. this._onAfterShaderCompilationObserver = null;
  74275. }
  74276. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  74277. // Properties
  74278. /**
  74279. * Gets the perf counter used for GPU frame time
  74280. */
  74281. get: function () {
  74282. return this._gpuFrameTime;
  74283. },
  74284. enumerable: true,
  74285. configurable: true
  74286. });
  74287. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  74288. /**
  74289. * Gets the GPU frame time capture status
  74290. */
  74291. get: function () {
  74292. return this._captureGPUFrameTime;
  74293. },
  74294. /**
  74295. * Enable or disable the GPU frame time capture
  74296. */
  74297. set: function (value) {
  74298. var _this = this;
  74299. if (value === this._captureGPUFrameTime) {
  74300. return;
  74301. }
  74302. this._captureGPUFrameTime = value;
  74303. if (value) {
  74304. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  74305. if (!_this._gpuFrameTimeToken) {
  74306. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  74307. }
  74308. });
  74309. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  74310. if (!_this._gpuFrameTimeToken) {
  74311. return;
  74312. }
  74313. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  74314. if (time > -1) {
  74315. _this._gpuFrameTimeToken = null;
  74316. _this._gpuFrameTime.fetchNewFrame();
  74317. _this._gpuFrameTime.addCount(time, true);
  74318. }
  74319. });
  74320. }
  74321. else {
  74322. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74323. this._onBeginFrameObserver = null;
  74324. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74325. this._onEndFrameObserver = null;
  74326. }
  74327. },
  74328. enumerable: true,
  74329. configurable: true
  74330. });
  74331. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  74332. /**
  74333. * Gets the perf counter used for shader compilation time
  74334. */
  74335. get: function () {
  74336. return this._shaderCompilationTime;
  74337. },
  74338. enumerable: true,
  74339. configurable: true
  74340. });
  74341. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  74342. /**
  74343. * Gets the shader compilation time capture status
  74344. */
  74345. get: function () {
  74346. return this._captureShaderCompilationTime;
  74347. },
  74348. /**
  74349. * Enable or disable the shader compilation time capture
  74350. */
  74351. set: function (value) {
  74352. var _this = this;
  74353. if (value === this._captureShaderCompilationTime) {
  74354. return;
  74355. }
  74356. this._captureShaderCompilationTime = value;
  74357. if (value) {
  74358. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  74359. _this._shaderCompilationTime.fetchNewFrame();
  74360. _this._shaderCompilationTime.beginMonitoring();
  74361. });
  74362. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  74363. _this._shaderCompilationTime.endMonitoring();
  74364. });
  74365. }
  74366. else {
  74367. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74368. this._onBeforeShaderCompilationObserver = null;
  74369. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74370. this._onAfterShaderCompilationObserver = null;
  74371. }
  74372. },
  74373. enumerable: true,
  74374. configurable: true
  74375. });
  74376. EngineInstrumentation.prototype.dispose = function () {
  74377. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74378. this._onBeginFrameObserver = null;
  74379. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74380. this._onEndFrameObserver = null;
  74381. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74382. this._onBeforeShaderCompilationObserver = null;
  74383. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74384. this._onAfterShaderCompilationObserver = null;
  74385. this.engine = null;
  74386. };
  74387. return EngineInstrumentation;
  74388. }());
  74389. BABYLON.EngineInstrumentation = EngineInstrumentation;
  74390. })(BABYLON || (BABYLON = {}));
  74391. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  74392. var BABYLON;
  74393. (function (BABYLON) {
  74394. /**
  74395. * This class can be used to get instrumentation data from a Babylon engine
  74396. */
  74397. var SceneInstrumentation = /** @class */ (function () {
  74398. function SceneInstrumentation(scene) {
  74399. var _this = this;
  74400. this.scene = scene;
  74401. this._captureActiveMeshesEvaluationTime = false;
  74402. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  74403. this._captureRenderTargetsRenderTime = false;
  74404. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  74405. this._captureFrameTime = false;
  74406. this._frameTime = new BABYLON.PerfCounter();
  74407. this._captureRenderTime = false;
  74408. this._renderTime = new BABYLON.PerfCounter();
  74409. this._captureInterFrameTime = false;
  74410. this._interFrameTime = new BABYLON.PerfCounter();
  74411. this._captureParticlesRenderTime = false;
  74412. this._particlesRenderTime = new BABYLON.PerfCounter();
  74413. this._captureSpritesRenderTime = false;
  74414. this._spritesRenderTime = new BABYLON.PerfCounter();
  74415. this._capturePhysicsTime = false;
  74416. this._physicsTime = new BABYLON.PerfCounter();
  74417. this._captureAnimationsTime = false;
  74418. this._animationsTime = new BABYLON.PerfCounter();
  74419. // Observers
  74420. this._onBeforeActiveMeshesEvaluationObserver = null;
  74421. this._onAfterActiveMeshesEvaluationObserver = null;
  74422. this._onBeforeRenderTargetsRenderObserver = null;
  74423. this._onAfterRenderTargetsRenderObserver = null;
  74424. this._onAfterRenderObserver = null;
  74425. this._onBeforeDrawPhaseObserver = null;
  74426. this._onAfterDrawPhaseObserver = null;
  74427. this._onBeforeAnimationsObserver = null;
  74428. this._onBeforeParticlesRenderingObserver = null;
  74429. this._onAfterParticlesRenderingObserver = null;
  74430. this._onBeforeSpritesRenderingObserver = null;
  74431. this._onAfterSpritesRenderingObserver = null;
  74432. this._onBeforePhysicsObserver = null;
  74433. this._onAfterPhysicsObserver = null;
  74434. this._onAfterAnimationsObserver = null;
  74435. // Before render
  74436. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  74437. if (_this._captureActiveMeshesEvaluationTime) {
  74438. _this._activeMeshesEvaluationTime.fetchNewFrame();
  74439. }
  74440. if (_this._captureRenderTargetsRenderTime) {
  74441. _this._renderTargetsRenderTime.fetchNewFrame();
  74442. }
  74443. if (_this._captureFrameTime) {
  74444. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  74445. _this._frameTime.beginMonitoring();
  74446. }
  74447. if (_this._captureInterFrameTime) {
  74448. _this._interFrameTime.endMonitoring();
  74449. }
  74450. if (_this._captureParticlesRenderTime) {
  74451. _this._particlesRenderTime.fetchNewFrame();
  74452. }
  74453. if (_this._captureSpritesRenderTime) {
  74454. _this._spritesRenderTime.fetchNewFrame();
  74455. }
  74456. if (_this._captureAnimationsTime) {
  74457. _this._animationsTime.beginMonitoring();
  74458. }
  74459. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  74460. });
  74461. // After render
  74462. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  74463. if (_this._captureFrameTime) {
  74464. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  74465. _this._frameTime.endMonitoring();
  74466. }
  74467. if (_this._captureRenderTime) {
  74468. _this._renderTime.endMonitoring(false);
  74469. }
  74470. if (_this._captureInterFrameTime) {
  74471. _this._interFrameTime.beginMonitoring();
  74472. }
  74473. });
  74474. }
  74475. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  74476. // Properties
  74477. /**
  74478. * Gets the perf counter used for active meshes evaluation time
  74479. */
  74480. get: function () {
  74481. return this._activeMeshesEvaluationTime;
  74482. },
  74483. enumerable: true,
  74484. configurable: true
  74485. });
  74486. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  74487. /**
  74488. * Gets the active meshes evaluation time capture status
  74489. */
  74490. get: function () {
  74491. return this._captureActiveMeshesEvaluationTime;
  74492. },
  74493. /**
  74494. * Enable or disable the active meshes evaluation time capture
  74495. */
  74496. set: function (value) {
  74497. var _this = this;
  74498. if (value === this._captureActiveMeshesEvaluationTime) {
  74499. return;
  74500. }
  74501. this._captureActiveMeshesEvaluationTime = value;
  74502. if (value) {
  74503. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  74504. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  74505. _this._activeMeshesEvaluationTime.beginMonitoring();
  74506. });
  74507. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  74508. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  74509. _this._activeMeshesEvaluationTime.endMonitoring();
  74510. });
  74511. }
  74512. else {
  74513. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74514. this._onBeforeActiveMeshesEvaluationObserver = null;
  74515. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74516. this._onAfterActiveMeshesEvaluationObserver = null;
  74517. }
  74518. },
  74519. enumerable: true,
  74520. configurable: true
  74521. });
  74522. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  74523. /**
  74524. * Gets the perf counter used for render targets render time
  74525. */
  74526. get: function () {
  74527. return this._renderTargetsRenderTime;
  74528. },
  74529. enumerable: true,
  74530. configurable: true
  74531. });
  74532. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  74533. /**
  74534. * Gets the render targets render time capture status
  74535. */
  74536. get: function () {
  74537. return this._captureRenderTargetsRenderTime;
  74538. },
  74539. /**
  74540. * Enable or disable the render targets render time capture
  74541. */
  74542. set: function (value) {
  74543. var _this = this;
  74544. if (value === this._captureRenderTargetsRenderTime) {
  74545. return;
  74546. }
  74547. this._captureRenderTargetsRenderTime = value;
  74548. if (value) {
  74549. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  74550. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  74551. _this._renderTargetsRenderTime.beginMonitoring();
  74552. });
  74553. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  74554. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  74555. _this._renderTargetsRenderTime.endMonitoring(false);
  74556. });
  74557. }
  74558. else {
  74559. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74560. this._onBeforeRenderTargetsRenderObserver = null;
  74561. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74562. this._onAfterRenderTargetsRenderObserver = null;
  74563. }
  74564. },
  74565. enumerable: true,
  74566. configurable: true
  74567. });
  74568. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  74569. /**
  74570. * Gets the perf counter used for particles render time
  74571. */
  74572. get: function () {
  74573. return this._particlesRenderTime;
  74574. },
  74575. enumerable: true,
  74576. configurable: true
  74577. });
  74578. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  74579. /**
  74580. * Gets the particles render time capture status
  74581. */
  74582. get: function () {
  74583. return this._captureParticlesRenderTime;
  74584. },
  74585. /**
  74586. * Enable or disable the particles render time capture
  74587. */
  74588. set: function (value) {
  74589. var _this = this;
  74590. if (value === this._captureParticlesRenderTime) {
  74591. return;
  74592. }
  74593. this._captureParticlesRenderTime = value;
  74594. if (value) {
  74595. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  74596. BABYLON.Tools.StartPerformanceCounter("Particles");
  74597. _this._particlesRenderTime.beginMonitoring();
  74598. });
  74599. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  74600. BABYLON.Tools.EndPerformanceCounter("Particles");
  74601. _this._particlesRenderTime.endMonitoring(false);
  74602. });
  74603. }
  74604. else {
  74605. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  74606. this._onBeforeParticlesRenderingObserver = null;
  74607. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  74608. this._onAfterParticlesRenderingObserver = null;
  74609. }
  74610. },
  74611. enumerable: true,
  74612. configurable: true
  74613. });
  74614. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  74615. /**
  74616. * Gets the perf counter used for sprites render time
  74617. */
  74618. get: function () {
  74619. return this._spritesRenderTime;
  74620. },
  74621. enumerable: true,
  74622. configurable: true
  74623. });
  74624. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  74625. /**
  74626. * Gets the sprites render time capture status
  74627. */
  74628. get: function () {
  74629. return this._captureSpritesRenderTime;
  74630. },
  74631. /**
  74632. * Enable or disable the sprites render time capture
  74633. */
  74634. set: function (value) {
  74635. var _this = this;
  74636. if (value === this._captureSpritesRenderTime) {
  74637. return;
  74638. }
  74639. this._captureSpritesRenderTime = value;
  74640. if (value) {
  74641. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  74642. BABYLON.Tools.StartPerformanceCounter("Sprites");
  74643. _this._spritesRenderTime.beginMonitoring();
  74644. });
  74645. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  74646. BABYLON.Tools.EndPerformanceCounter("Sprites");
  74647. _this._spritesRenderTime.endMonitoring(false);
  74648. });
  74649. }
  74650. else {
  74651. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  74652. this._onBeforeSpritesRenderingObserver = null;
  74653. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  74654. this._onAfterSpritesRenderingObserver = null;
  74655. }
  74656. },
  74657. enumerable: true,
  74658. configurable: true
  74659. });
  74660. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  74661. /**
  74662. * Gets the perf counter used for physics time
  74663. */
  74664. get: function () {
  74665. return this._physicsTime;
  74666. },
  74667. enumerable: true,
  74668. configurable: true
  74669. });
  74670. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  74671. /**
  74672. * Gets the physics time capture status
  74673. */
  74674. get: function () {
  74675. return this._capturePhysicsTime;
  74676. },
  74677. /**
  74678. * Enable or disable the physics time capture
  74679. */
  74680. set: function (value) {
  74681. var _this = this;
  74682. if (value === this._capturePhysicsTime) {
  74683. return;
  74684. }
  74685. this._capturePhysicsTime = value;
  74686. if (value) {
  74687. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  74688. BABYLON.Tools.StartPerformanceCounter("Physics");
  74689. _this._physicsTime.beginMonitoring();
  74690. });
  74691. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  74692. BABYLON.Tools.EndPerformanceCounter("Physics");
  74693. _this._physicsTime.endMonitoring();
  74694. });
  74695. }
  74696. else {
  74697. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  74698. this._onBeforePhysicsObserver = null;
  74699. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  74700. this._onAfterPhysicsObserver = null;
  74701. }
  74702. },
  74703. enumerable: true,
  74704. configurable: true
  74705. });
  74706. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  74707. /**
  74708. * Gets the perf counter used for animations time
  74709. */
  74710. get: function () {
  74711. return this._animationsTime;
  74712. },
  74713. enumerable: true,
  74714. configurable: true
  74715. });
  74716. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  74717. /**
  74718. * Gets the animations time capture status
  74719. */
  74720. get: function () {
  74721. return this._captureAnimationsTime;
  74722. },
  74723. /**
  74724. * Enable or disable the animations time capture
  74725. */
  74726. set: function (value) {
  74727. var _this = this;
  74728. if (value === this._captureAnimationsTime) {
  74729. return;
  74730. }
  74731. this._captureAnimationsTime = value;
  74732. if (value) {
  74733. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  74734. _this._animationsTime.endMonitoring();
  74735. });
  74736. }
  74737. else {
  74738. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  74739. this._onAfterAnimationsObserver = null;
  74740. }
  74741. },
  74742. enumerable: true,
  74743. configurable: true
  74744. });
  74745. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  74746. /**
  74747. * Gets the perf counter used for frame time capture
  74748. */
  74749. get: function () {
  74750. return this._frameTime;
  74751. },
  74752. enumerable: true,
  74753. configurable: true
  74754. });
  74755. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  74756. /**
  74757. * Gets the frame time capture status
  74758. */
  74759. get: function () {
  74760. return this._captureFrameTime;
  74761. },
  74762. /**
  74763. * Enable or disable the frame time capture
  74764. */
  74765. set: function (value) {
  74766. this._captureFrameTime = value;
  74767. },
  74768. enumerable: true,
  74769. configurable: true
  74770. });
  74771. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  74772. /**
  74773. * Gets the perf counter used for inter-frames time capture
  74774. */
  74775. get: function () {
  74776. return this._interFrameTime;
  74777. },
  74778. enumerable: true,
  74779. configurable: true
  74780. });
  74781. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  74782. /**
  74783. * Gets the inter-frames time capture status
  74784. */
  74785. get: function () {
  74786. return this._captureInterFrameTime;
  74787. },
  74788. /**
  74789. * Enable or disable the inter-frames time capture
  74790. */
  74791. set: function (value) {
  74792. this._captureInterFrameTime = value;
  74793. },
  74794. enumerable: true,
  74795. configurable: true
  74796. });
  74797. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  74798. /**
  74799. * Gets the perf counter used for render time capture
  74800. */
  74801. get: function () {
  74802. return this._renderTime;
  74803. },
  74804. enumerable: true,
  74805. configurable: true
  74806. });
  74807. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  74808. /**
  74809. * Gets the render time capture status
  74810. */
  74811. get: function () {
  74812. return this._captureRenderTime;
  74813. },
  74814. /**
  74815. * Enable or disable the render time capture
  74816. */
  74817. set: function (value) {
  74818. var _this = this;
  74819. if (value === this._captureRenderTime) {
  74820. return;
  74821. }
  74822. this._captureRenderTime = value;
  74823. if (value) {
  74824. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  74825. _this._renderTime.beginMonitoring();
  74826. BABYLON.Tools.StartPerformanceCounter("Main render");
  74827. });
  74828. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  74829. _this._renderTime.endMonitoring(false);
  74830. BABYLON.Tools.EndPerformanceCounter("Main render");
  74831. });
  74832. }
  74833. else {
  74834. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  74835. this._onBeforeDrawPhaseObserver = null;
  74836. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  74837. this._onAfterDrawPhaseObserver = null;
  74838. }
  74839. },
  74840. enumerable: true,
  74841. configurable: true
  74842. });
  74843. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  74844. /**
  74845. * Gets the perf counter used for frame time capture
  74846. */
  74847. get: function () {
  74848. return this.scene.getEngine()._drawCalls;
  74849. },
  74850. enumerable: true,
  74851. configurable: true
  74852. });
  74853. SceneInstrumentation.prototype.dispose = function () {
  74854. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74855. this._onAfterRenderObserver = null;
  74856. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74857. this._onBeforeActiveMeshesEvaluationObserver = null;
  74858. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74859. this._onAfterActiveMeshesEvaluationObserver = null;
  74860. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74861. this._onBeforeRenderTargetsRenderObserver = null;
  74862. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74863. this._onAfterRenderTargetsRenderObserver = null;
  74864. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  74865. this._onBeforeAnimationsObserver = null;
  74866. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  74867. this._onBeforeParticlesRenderingObserver = null;
  74868. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  74869. this._onAfterParticlesRenderingObserver = null;
  74870. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  74871. this._onBeforeSpritesRenderingObserver = null;
  74872. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  74873. this._onAfterSpritesRenderingObserver = null;
  74874. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  74875. this._onBeforeDrawPhaseObserver = null;
  74876. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  74877. this._onAfterDrawPhaseObserver = null;
  74878. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  74879. this._onBeforePhysicsObserver = null;
  74880. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  74881. this._onAfterPhysicsObserver = null;
  74882. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  74883. this._onAfterAnimationsObserver = null;
  74884. this.scene = null;
  74885. };
  74886. return SceneInstrumentation;
  74887. }());
  74888. BABYLON.SceneInstrumentation = SceneInstrumentation;
  74889. })(BABYLON || (BABYLON = {}));
  74890. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  74891. var BABYLON;
  74892. (function (BABYLON) {
  74893. var _TimeToken = /** @class */ (function () {
  74894. function _TimeToken() {
  74895. this._timeElapsedQueryEnded = false;
  74896. }
  74897. return _TimeToken;
  74898. }());
  74899. BABYLON._TimeToken = _TimeToken;
  74900. })(BABYLON || (BABYLON = {}));
  74901. //# sourceMappingURL=babylon.timeToken.js.map
  74902. 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;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\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 AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\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#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}"};
  74903. 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}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  74904. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  74905. var BABYLON;
  74906. (function (BABYLON) {
  74907. var GridMaterialDefines = /** @class */ (function (_super) {
  74908. __extends(GridMaterialDefines, _super);
  74909. function GridMaterialDefines() {
  74910. var _this = _super.call(this) || this;
  74911. _this.TRANSPARENT = false;
  74912. _this.FOG = false;
  74913. _this.PREMULTIPLYALPHA = false;
  74914. _this.rebuild();
  74915. return _this;
  74916. }
  74917. return GridMaterialDefines;
  74918. }(BABYLON.MaterialDefines));
  74919. /**
  74920. * The grid materials allows you to wrap any shape with a grid.
  74921. * Colors are customizable.
  74922. */
  74923. var GridMaterial = /** @class */ (function (_super) {
  74924. __extends(GridMaterial, _super);
  74925. /**
  74926. * constructor
  74927. * @param name The name given to the material in order to identify it afterwards.
  74928. * @param scene The scene the material is used in.
  74929. */
  74930. function GridMaterial(name, scene) {
  74931. var _this = _super.call(this, name, scene) || this;
  74932. /**
  74933. * Main color of the grid (e.g. between lines)
  74934. */
  74935. _this.mainColor = BABYLON.Color3.Black();
  74936. /**
  74937. * Color of the grid lines.
  74938. */
  74939. _this.lineColor = BABYLON.Color3.Teal();
  74940. /**
  74941. * The scale of the grid compared to unit.
  74942. */
  74943. _this.gridRatio = 1.0;
  74944. /**
  74945. * Allows setting an offset for the grid lines.
  74946. */
  74947. _this.gridOffset = BABYLON.Vector3.Zero();
  74948. /**
  74949. * The frequency of thicker lines.
  74950. */
  74951. _this.majorUnitFrequency = 10;
  74952. /**
  74953. * The visibility of minor units in the grid.
  74954. */
  74955. _this.minorUnitVisibility = 0.33;
  74956. /**
  74957. * The grid opacity outside of the lines.
  74958. */
  74959. _this.opacity = 1.0;
  74960. /**
  74961. * Determine RBG output is premultiplied by alpha value.
  74962. */
  74963. _this.preMultiplyAlpha = false;
  74964. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  74965. return _this;
  74966. }
  74967. /**
  74968. * Returns wehter or not the grid requires alpha blending.
  74969. */
  74970. GridMaterial.prototype.needAlphaBlending = function () {
  74971. return this.opacity < 1.0;
  74972. };
  74973. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74974. if (this.isFrozen) {
  74975. if (this._wasPreviouslyReady && subMesh.effect) {
  74976. return true;
  74977. }
  74978. }
  74979. if (!subMesh._materialDefines) {
  74980. subMesh._materialDefines = new GridMaterialDefines();
  74981. }
  74982. var defines = subMesh._materialDefines;
  74983. var scene = this.getScene();
  74984. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  74985. if (this._renderId === scene.getRenderId()) {
  74986. return true;
  74987. }
  74988. }
  74989. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  74990. defines.TRANSPARENT = !defines.TRANSPARENT;
  74991. defines.markAsUnprocessed();
  74992. }
  74993. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  74994. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  74995. defines.markAsUnprocessed();
  74996. }
  74997. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  74998. // Get correct effect
  74999. if (defines.isDirty) {
  75000. defines.markAsProcessed();
  75001. scene.resetCachedMaterial();
  75002. // Attributes
  75003. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75004. // Defines
  75005. var join = defines.toString();
  75006. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  75007. }
  75008. if (!subMesh.effect || !subMesh.effect.isReady()) {
  75009. return false;
  75010. }
  75011. this._renderId = scene.getRenderId();
  75012. this._wasPreviouslyReady = true;
  75013. return true;
  75014. };
  75015. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  75016. var scene = this.getScene();
  75017. var defines = subMesh._materialDefines;
  75018. if (!defines) {
  75019. return;
  75020. }
  75021. var effect = subMesh.effect;
  75022. if (!effect) {
  75023. return;
  75024. }
  75025. this._activeEffect = effect;
  75026. // Matrices
  75027. this.bindOnlyWorldMatrix(world);
  75028. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  75029. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  75030. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  75031. // Uniforms
  75032. if (this._mustRebind(scene, effect)) {
  75033. this._activeEffect.setColor3("mainColor", this.mainColor);
  75034. this._activeEffect.setColor3("lineColor", this.lineColor);
  75035. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  75036. this._gridControl.x = this.gridRatio;
  75037. this._gridControl.y = Math.round(this.majorUnitFrequency);
  75038. this._gridControl.z = this.minorUnitVisibility;
  75039. this._gridControl.w = this.opacity;
  75040. this._activeEffect.setVector4("gridControl", this._gridControl);
  75041. }
  75042. // Fog
  75043. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  75044. this._afterBind(mesh, this._activeEffect);
  75045. };
  75046. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  75047. _super.prototype.dispose.call(this, forceDisposeEffect);
  75048. };
  75049. GridMaterial.prototype.clone = function (name) {
  75050. var _this = this;
  75051. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  75052. };
  75053. GridMaterial.prototype.serialize = function () {
  75054. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75055. serializationObject.customType = "BABYLON.GridMaterial";
  75056. return serializationObject;
  75057. };
  75058. GridMaterial.prototype.getClassName = function () {
  75059. return "GridMaterial";
  75060. };
  75061. GridMaterial.Parse = function (source, scene, rootUrl) {
  75062. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  75063. };
  75064. __decorate([
  75065. BABYLON.serializeAsColor3()
  75066. ], GridMaterial.prototype, "mainColor", void 0);
  75067. __decorate([
  75068. BABYLON.serializeAsColor3()
  75069. ], GridMaterial.prototype, "lineColor", void 0);
  75070. __decorate([
  75071. BABYLON.serialize()
  75072. ], GridMaterial.prototype, "gridRatio", void 0);
  75073. __decorate([
  75074. BABYLON.serializeAsColor3()
  75075. ], GridMaterial.prototype, "gridOffset", void 0);
  75076. __decorate([
  75077. BABYLON.serialize()
  75078. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  75079. __decorate([
  75080. BABYLON.serialize()
  75081. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  75082. __decorate([
  75083. BABYLON.serialize()
  75084. ], GridMaterial.prototype, "opacity", void 0);
  75085. __decorate([
  75086. BABYLON.serialize()
  75087. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  75088. return GridMaterial;
  75089. }(BABYLON.PushMaterial));
  75090. BABYLON.GridMaterial = GridMaterial;
  75091. })(BABYLON || (BABYLON = {}));
  75092. //# sourceMappingURL=babylon.gridmaterial.js.map
  75093. 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}";
  75094. 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}";
  75095. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  75096. var BABYLON;
  75097. (function (BABYLON) {
  75098. /**
  75099. * Background material defines definition.
  75100. */
  75101. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  75102. __extends(BackgroundMaterialDefines, _super);
  75103. /**
  75104. * Constructor of the defines.
  75105. */
  75106. function BackgroundMaterialDefines() {
  75107. var _this = _super.call(this) || this;
  75108. /**
  75109. * True if the diffuse texture is in use.
  75110. */
  75111. _this.DIFFUSE = false;
  75112. /**
  75113. * The direct UV channel to use.
  75114. */
  75115. _this.DIFFUSEDIRECTUV = 0;
  75116. /**
  75117. * True if the diffuse texture is in gamma space.
  75118. */
  75119. _this.GAMMADIFFUSE = false;
  75120. /**
  75121. * True if the diffuse texture has opacity in the alpha channel.
  75122. */
  75123. _this.DIFFUSEHASALPHA = false;
  75124. /**
  75125. * True if you want the material to fade to transparent at grazing angle.
  75126. */
  75127. _this.OPACITYFRESNEL = false;
  75128. /**
  75129. * True if an extra blur needs to be added in the reflection.
  75130. */
  75131. _this.REFLECTIONBLUR = false;
  75132. /**
  75133. * False if the current Webgl implementation does not support the texture lod extension.
  75134. */
  75135. _this.TEXTURELODSUPPORT = false;
  75136. /**
  75137. * True to ensure the data are premultiplied.
  75138. */
  75139. _this.PREMULTIPLYALPHA = false;
  75140. /**
  75141. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  75142. */
  75143. _this.USERGBCOLOR = false;
  75144. // Image Processing Configuration.
  75145. _this.IMAGEPROCESSING = false;
  75146. _this.VIGNETTE = false;
  75147. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  75148. _this.VIGNETTEBLENDMODEOPAQUE = false;
  75149. _this.TONEMAPPING = false;
  75150. _this.CONTRAST = false;
  75151. _this.COLORCURVES = false;
  75152. _this.COLORGRADING = false;
  75153. _this.COLORGRADING3D = false;
  75154. _this.SAMPLER3DGREENDEPTH = false;
  75155. _this.SAMPLER3DBGRMAP = false;
  75156. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  75157. _this.EXPOSURE = false;
  75158. // Reflection.
  75159. _this.REFLECTION = false;
  75160. _this.REFLECTIONMAP_3D = false;
  75161. _this.REFLECTIONMAP_SPHERICAL = false;
  75162. _this.REFLECTIONMAP_PLANAR = false;
  75163. _this.REFLECTIONMAP_CUBIC = false;
  75164. _this.REFLECTIONMAP_PROJECTION = false;
  75165. _this.REFLECTIONMAP_SKYBOX = false;
  75166. _this.REFLECTIONMAP_EXPLICIT = false;
  75167. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75168. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75169. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75170. _this.INVERTCUBICMAP = false;
  75171. _this.REFLECTIONMAP_OPPOSITEZ = false;
  75172. _this.LODINREFLECTIONALPHA = false;
  75173. _this.GAMMAREFLECTION = false;
  75174. // Default BJS.
  75175. _this.MAINUV1 = false;
  75176. _this.MAINUV2 = false;
  75177. _this.UV1 = false;
  75178. _this.UV2 = false;
  75179. _this.CLIPPLANE = false;
  75180. _this.POINTSIZE = false;
  75181. _this.FOG = false;
  75182. _this.NORMAL = false;
  75183. _this.NUM_BONE_INFLUENCERS = 0;
  75184. _this.BonesPerMesh = 0;
  75185. _this.INSTANCES = false;
  75186. _this.SHADOWFLOAT = false;
  75187. _this.rebuild();
  75188. return _this;
  75189. }
  75190. return BackgroundMaterialDefines;
  75191. }(BABYLON.MaterialDefines));
  75192. /**
  75193. * Background material
  75194. */
  75195. var BackgroundMaterial = /** @class */ (function (_super) {
  75196. __extends(BackgroundMaterial, _super);
  75197. /**
  75198. * constructor
  75199. * @param name The name of the material
  75200. * @param scene The scene to add the material to
  75201. */
  75202. function BackgroundMaterial(name, scene) {
  75203. var _this = _super.call(this, name, scene) || this;
  75204. _this.primaryColor = BABYLON.Color3.White();
  75205. _this.primaryLevel = 1;
  75206. _this.secondaryColor = BABYLON.Color3.Gray();
  75207. _this.secondaryLevel = 1;
  75208. _this.tertiaryColor = BABYLON.Color3.Black();
  75209. _this.tertiaryLevel = 1;
  75210. _this.reflectionTexture = null;
  75211. _this.reflectionBlur = 0;
  75212. _this.diffuseTexture = null;
  75213. /**
  75214. * Specify the list of lights casting shadow on the material.
  75215. * All scene shadow lights will be included if null.
  75216. */
  75217. _this._shadowLights = null;
  75218. _this.shadowLights = null;
  75219. _this.shadowBlurScale = 1;
  75220. _this.shadowLevel = 0;
  75221. _this.opacityFresnel = true;
  75222. _this.useRGBColor = true;
  75223. /**
  75224. * Number of Simultaneous lights allowed on the material.
  75225. */
  75226. _this._maxSimultaneousLights = 4;
  75227. _this.maxSimultaneousLights = 4;
  75228. /**
  75229. * Keep track of the image processing observer to allow dispose and replace.
  75230. */
  75231. _this._imageProcessingObserver = null;
  75232. // Temp values kept as cache in the material.
  75233. _this._renderTargets = new BABYLON.SmartArray(16);
  75234. // Setup the default processing configuration to the scene.
  75235. _this._attachImageProcessingConfiguration(null);
  75236. _this.getRenderTargetTextures = function () {
  75237. _this._renderTargets.reset();
  75238. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  75239. _this._renderTargets.push(_this._diffuseTexture);
  75240. }
  75241. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  75242. _this._renderTargets.push(_this._reflectionTexture);
  75243. }
  75244. return _this._renderTargets;
  75245. };
  75246. return _this;
  75247. }
  75248. /**
  75249. * Attaches a new image processing configuration to the PBR Material.
  75250. * @param configuration (if null the scene configuration will be use)
  75251. */
  75252. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  75253. var _this = this;
  75254. if (configuration === this._imageProcessingConfiguration) {
  75255. return;
  75256. }
  75257. // Detaches observer.
  75258. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75259. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75260. }
  75261. // Pick the scene configuration if needed.
  75262. if (!configuration) {
  75263. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  75264. }
  75265. else {
  75266. this._imageProcessingConfiguration = configuration;
  75267. }
  75268. // Attaches observer.
  75269. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  75270. _this._markAllSubMeshesAsImageProcessingDirty();
  75271. });
  75272. };
  75273. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  75274. /**
  75275. * Gets the image processing configuration used either in this material.
  75276. */
  75277. get: function () {
  75278. return this._imageProcessingConfiguration;
  75279. },
  75280. /**
  75281. * Sets the Default image processing configuration used either in the this material.
  75282. *
  75283. * If sets to null, the scene one is in use.
  75284. */
  75285. set: function (value) {
  75286. this._attachImageProcessingConfiguration(value);
  75287. // Ensure the effect will be rebuilt.
  75288. this._markAllSubMeshesAsTexturesDirty();
  75289. },
  75290. enumerable: true,
  75291. configurable: true
  75292. });
  75293. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  75294. /**
  75295. * Gets wether the color curves effect is enabled.
  75296. */
  75297. get: function () {
  75298. return this.imageProcessingConfiguration.colorCurvesEnabled;
  75299. },
  75300. /**
  75301. * Sets wether the color curves effect is enabled.
  75302. */
  75303. set: function (value) {
  75304. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  75305. },
  75306. enumerable: true,
  75307. configurable: true
  75308. });
  75309. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  75310. /**
  75311. * Gets wether the color grading effect is enabled.
  75312. */
  75313. get: function () {
  75314. return this.imageProcessingConfiguration.colorGradingEnabled;
  75315. },
  75316. /**
  75317. * Gets wether the color grading effect is enabled.
  75318. */
  75319. set: function (value) {
  75320. this.imageProcessingConfiguration.colorGradingEnabled = value;
  75321. },
  75322. enumerable: true,
  75323. configurable: true
  75324. });
  75325. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  75326. /**
  75327. * Gets wether tonemapping is enabled or not.
  75328. */
  75329. get: function () {
  75330. return this._imageProcessingConfiguration.toneMappingEnabled;
  75331. },
  75332. /**
  75333. * Sets wether tonemapping is enabled or not
  75334. */
  75335. set: function (value) {
  75336. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75337. },
  75338. enumerable: true,
  75339. configurable: true
  75340. });
  75341. ;
  75342. ;
  75343. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  75344. /**
  75345. * The camera exposure used on this material.
  75346. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  75347. * This corresponds to a photographic exposure.
  75348. */
  75349. get: function () {
  75350. return this._imageProcessingConfiguration.exposure;
  75351. },
  75352. /**
  75353. * The camera exposure used on this material.
  75354. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  75355. * This corresponds to a photographic exposure.
  75356. */
  75357. set: function (value) {
  75358. this._imageProcessingConfiguration.exposure = value;
  75359. },
  75360. enumerable: true,
  75361. configurable: true
  75362. });
  75363. ;
  75364. ;
  75365. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  75366. /**
  75367. * Gets The camera contrast used on this material.
  75368. */
  75369. get: function () {
  75370. return this._imageProcessingConfiguration.contrast;
  75371. },
  75372. /**
  75373. * Sets The camera contrast used on this material.
  75374. */
  75375. set: function (value) {
  75376. this._imageProcessingConfiguration.contrast = value;
  75377. },
  75378. enumerable: true,
  75379. configurable: true
  75380. });
  75381. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  75382. /**
  75383. * Gets the Color Grading 2D Lookup Texture.
  75384. */
  75385. get: function () {
  75386. return this._imageProcessingConfiguration.colorGradingTexture;
  75387. },
  75388. /**
  75389. * Sets the Color Grading 2D Lookup Texture.
  75390. */
  75391. set: function (value) {
  75392. this.imageProcessingConfiguration.colorGradingTexture = value;
  75393. },
  75394. enumerable: true,
  75395. configurable: true
  75396. });
  75397. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  75398. /**
  75399. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  75400. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  75401. * 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;
  75402. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  75403. */
  75404. get: function () {
  75405. return this.imageProcessingConfiguration.colorCurves;
  75406. },
  75407. /**
  75408. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  75409. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  75410. * 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;
  75411. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  75412. */
  75413. set: function (value) {
  75414. this.imageProcessingConfiguration.colorCurves = value;
  75415. },
  75416. enumerable: true,
  75417. configurable: true
  75418. });
  75419. /**
  75420. * The entire material has been created in order to prevent overdraw.
  75421. * @returns false
  75422. */
  75423. BackgroundMaterial.prototype.needAlphaTesting = function () {
  75424. return false;
  75425. };
  75426. /**
  75427. * The entire material has been created in order to prevent overdraw.
  75428. * @returns true if blending is enable
  75429. */
  75430. BackgroundMaterial.prototype.needAlphaBlending = function () {
  75431. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  75432. };
  75433. /**
  75434. * Checks wether the material is ready to be rendered for a given mesh.
  75435. * @param mesh The mesh to render
  75436. * @param subMesh The submesh to check against
  75437. * @param useInstances Specify wether or not the material is used with instances
  75438. */
  75439. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  75440. var _this = this;
  75441. if (useInstances === void 0) { useInstances = false; }
  75442. if (subMesh.effect && this.isFrozen) {
  75443. if (this._wasPreviouslyReady) {
  75444. return true;
  75445. }
  75446. }
  75447. if (!subMesh._materialDefines) {
  75448. subMesh._materialDefines = new BackgroundMaterialDefines();
  75449. }
  75450. var scene = this.getScene();
  75451. var defines = subMesh._materialDefines;
  75452. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  75453. if (defines._renderId === scene.getRenderId()) {
  75454. return true;
  75455. }
  75456. }
  75457. var engine = scene.getEngine();
  75458. // Lights
  75459. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  75460. defines._needNormals = true;
  75461. // Textures
  75462. if (defines._areTexturesDirty) {
  75463. defines._needUVs = false;
  75464. if (scene.texturesEnabled) {
  75465. if (scene.getEngine().getCaps().textureLOD) {
  75466. defines.TEXTURELODSUPPORT = true;
  75467. }
  75468. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75469. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  75470. return false;
  75471. }
  75472. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  75473. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  75474. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  75475. defines.OPACITYFRESNEL = this._opacityFresnel;
  75476. }
  75477. else {
  75478. defines.DIFFUSE = false;
  75479. defines.DIFFUSEHASALPHA = false;
  75480. defines.GAMMADIFFUSE = false;
  75481. defines.OPACITYFRESNEL = false;
  75482. }
  75483. var reflectionTexture = this._reflectionTexture;
  75484. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75485. if (!reflectionTexture.isReadyOrNotBlocking()) {
  75486. return false;
  75487. }
  75488. defines.REFLECTION = true;
  75489. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  75490. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  75491. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  75492. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  75493. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  75494. defines.INVERTCUBICMAP = true;
  75495. }
  75496. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  75497. switch (reflectionTexture.coordinatesMode) {
  75498. case BABYLON.Texture.CUBIC_MODE:
  75499. case BABYLON.Texture.INVCUBIC_MODE:
  75500. defines.REFLECTIONMAP_CUBIC = true;
  75501. break;
  75502. case BABYLON.Texture.EXPLICIT_MODE:
  75503. defines.REFLECTIONMAP_EXPLICIT = true;
  75504. break;
  75505. case BABYLON.Texture.PLANAR_MODE:
  75506. defines.REFLECTIONMAP_PLANAR = true;
  75507. break;
  75508. case BABYLON.Texture.PROJECTION_MODE:
  75509. defines.REFLECTIONMAP_PROJECTION = true;
  75510. break;
  75511. case BABYLON.Texture.SKYBOX_MODE:
  75512. defines.REFLECTIONMAP_SKYBOX = true;
  75513. break;
  75514. case BABYLON.Texture.SPHERICAL_MODE:
  75515. defines.REFLECTIONMAP_SPHERICAL = true;
  75516. break;
  75517. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  75518. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  75519. break;
  75520. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  75521. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  75522. break;
  75523. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  75524. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  75525. break;
  75526. }
  75527. }
  75528. else {
  75529. defines.REFLECTION = false;
  75530. defines.REFLECTIONBLUR = false;
  75531. defines.REFLECTIONMAP_3D = false;
  75532. defines.REFLECTIONMAP_SPHERICAL = false;
  75533. defines.REFLECTIONMAP_PLANAR = false;
  75534. defines.REFLECTIONMAP_CUBIC = false;
  75535. defines.REFLECTIONMAP_PROJECTION = false;
  75536. defines.REFLECTIONMAP_SKYBOX = false;
  75537. defines.REFLECTIONMAP_EXPLICIT = false;
  75538. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75539. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75540. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75541. defines.INVERTCUBICMAP = false;
  75542. defines.REFLECTIONMAP_OPPOSITEZ = false;
  75543. defines.LODINREFLECTIONALPHA = false;
  75544. defines.GAMMAREFLECTION = false;
  75545. }
  75546. }
  75547. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  75548. defines.USERGBCOLOR = this._useRGBColor;
  75549. }
  75550. if (defines._areImageProcessingDirty) {
  75551. if (!this._imageProcessingConfiguration.isReady()) {
  75552. return false;
  75553. }
  75554. this._imageProcessingConfiguration.prepareDefines(defines);
  75555. }
  75556. // Misc.
  75557. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  75558. // Values that need to be evaluated on every frame
  75559. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  75560. // Attribs
  75561. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  75562. if (mesh) {
  75563. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75564. mesh.createNormals(true);
  75565. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  75566. }
  75567. }
  75568. }
  75569. // Get correct effect
  75570. if (defines.isDirty) {
  75571. defines.markAsProcessed();
  75572. scene.resetCachedMaterial();
  75573. // Fallbacks
  75574. var fallbacks = new BABYLON.EffectFallbacks();
  75575. if (defines.FOG) {
  75576. fallbacks.addFallback(0, "FOG");
  75577. }
  75578. if (defines.POINTSIZE) {
  75579. fallbacks.addFallback(1, "POINTSIZE");
  75580. }
  75581. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  75582. if (defines.NUM_BONE_INFLUENCERS > 0) {
  75583. fallbacks.addCPUSkinningFallback(0, mesh);
  75584. }
  75585. //Attributes
  75586. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75587. if (defines.NORMAL) {
  75588. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75589. }
  75590. if (defines.UV1) {
  75591. attribs.push(BABYLON.VertexBuffer.UVKind);
  75592. }
  75593. if (defines.UV2) {
  75594. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75595. }
  75596. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  75597. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  75598. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  75599. "vFogInfos", "vFogColor", "pointSize",
  75600. "vClipPlane", "mBones",
  75601. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  75602. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  75603. "shadowLevel", "alpha",
  75604. "vDiffuseInfos", "diffuseMatrix",
  75605. ];
  75606. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  75607. var uniformBuffers = ["Material", "Scene"];
  75608. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  75609. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  75610. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  75611. uniformsNames: uniforms,
  75612. uniformBuffersNames: uniformBuffers,
  75613. samplers: samplers,
  75614. defines: defines,
  75615. maxSimultaneousLights: this._maxSimultaneousLights
  75616. });
  75617. var onCompiled = function (effect) {
  75618. if (_this.onCompiled) {
  75619. _this.onCompiled(effect);
  75620. }
  75621. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  75622. };
  75623. var join = defines.toString();
  75624. subMesh.setEffect(scene.getEngine().createEffect("background", {
  75625. attributes: attribs,
  75626. uniformsNames: uniforms,
  75627. uniformBuffersNames: uniformBuffers,
  75628. samplers: samplers,
  75629. defines: join,
  75630. fallbacks: fallbacks,
  75631. onCompiled: onCompiled,
  75632. onError: this.onError,
  75633. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  75634. }, engine), defines);
  75635. this.buildUniformLayout();
  75636. }
  75637. if (!subMesh.effect || !subMesh.effect.isReady()) {
  75638. return false;
  75639. }
  75640. defines._renderId = scene.getRenderId();
  75641. this._wasPreviouslyReady = true;
  75642. return true;
  75643. };
  75644. /**
  75645. * Build the uniform buffer used in the material.
  75646. */
  75647. BackgroundMaterial.prototype.buildUniformLayout = function () {
  75648. // Order is important !
  75649. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  75650. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  75651. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  75652. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  75653. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  75654. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  75655. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  75656. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  75657. this._uniformBuffer.addUniform("pointSize", 1);
  75658. this._uniformBuffer.addUniform("shadowLevel", 1);
  75659. this._uniformBuffer.addUniform("alpha", 1);
  75660. this._uniformBuffer.create();
  75661. };
  75662. /**
  75663. * Unbind the material.
  75664. */
  75665. BackgroundMaterial.prototype.unbind = function () {
  75666. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  75667. this._uniformBuffer.setTexture("diffuseSampler", null);
  75668. }
  75669. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  75670. this._uniformBuffer.setTexture("reflectionSampler", null);
  75671. }
  75672. _super.prototype.unbind.call(this);
  75673. };
  75674. /**
  75675. * Bind only the world matrix to the material.
  75676. * @param world The world matrix to bind.
  75677. */
  75678. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  75679. this._activeEffect.setMatrix("world", world);
  75680. };
  75681. /**
  75682. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  75683. * @param world The world matrix to bind.
  75684. * @param subMesh The submesh to bind for.
  75685. */
  75686. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  75687. var scene = this.getScene();
  75688. var defines = subMesh._materialDefines;
  75689. if (!defines) {
  75690. return;
  75691. }
  75692. var effect = subMesh.effect;
  75693. if (!effect) {
  75694. return;
  75695. }
  75696. this._activeEffect = effect;
  75697. // Matrices
  75698. this.bindOnlyWorldMatrix(world);
  75699. // Bones
  75700. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  75701. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  75702. if (mustRebind) {
  75703. this._uniformBuffer.bindToEffect(effect, "Material");
  75704. this.bindViewProjection(effect);
  75705. var reflectionTexture = this._reflectionTexture;
  75706. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  75707. // Texture uniforms
  75708. if (scene.texturesEnabled) {
  75709. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75710. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  75711. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  75712. }
  75713. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75714. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  75715. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  75716. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  75717. }
  75718. }
  75719. if (this.shadowLevel > 0) {
  75720. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  75721. }
  75722. this._uniformBuffer.updateFloat("alpha", this.alpha);
  75723. // Point size
  75724. if (this.pointsCloud) {
  75725. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  75726. }
  75727. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  75728. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  75729. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  75730. }
  75731. // Textures
  75732. if (scene.texturesEnabled) {
  75733. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75734. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  75735. }
  75736. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75737. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  75738. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75739. }
  75740. else if (!defines.REFLECTIONBLUR) {
  75741. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75742. }
  75743. else {
  75744. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  75745. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  75746. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  75747. }
  75748. }
  75749. }
  75750. // Clip plane
  75751. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  75752. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  75753. }
  75754. if (mustRebind || !this.isFrozen) {
  75755. if (scene.lightsEnabled) {
  75756. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  75757. }
  75758. // View
  75759. this.bindView(effect);
  75760. // Fog
  75761. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  75762. // image processing
  75763. this._imageProcessingConfiguration.bind(this._activeEffect);
  75764. }
  75765. this._uniformBuffer.update();
  75766. this._afterBind(mesh);
  75767. };
  75768. /**
  75769. * Dispose the material.
  75770. * @forceDisposeEffect Force disposal of the associated effect.
  75771. * @forceDisposeTextures Force disposal of the associated textures.
  75772. */
  75773. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  75774. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  75775. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  75776. if (forceDisposeTextures) {
  75777. if (this.diffuseTexture) {
  75778. this.diffuseTexture.dispose();
  75779. }
  75780. if (this.reflectionTexture) {
  75781. this.reflectionTexture.dispose();
  75782. }
  75783. }
  75784. this._renderTargets.dispose();
  75785. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75786. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75787. }
  75788. _super.prototype.dispose.call(this, forceDisposeEffect);
  75789. };
  75790. /**
  75791. * Clones the material.
  75792. * @name The cloned name.
  75793. * @returns The cloned material.
  75794. */
  75795. BackgroundMaterial.prototype.clone = function (name) {
  75796. var _this = this;
  75797. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  75798. };
  75799. /**
  75800. * Serializes the current material to its JSON representation.
  75801. * @returns The JSON representation.
  75802. */
  75803. BackgroundMaterial.prototype.serialize = function () {
  75804. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75805. serializationObject.customType = "BABYLON.BackgroundMaterial";
  75806. return serializationObject;
  75807. };
  75808. /**
  75809. * Gets the class name of the material
  75810. * @returns "BackgroundMaterial"
  75811. */
  75812. BackgroundMaterial.prototype.getClassName = function () {
  75813. return "BackgroundMaterial";
  75814. };
  75815. /**
  75816. * Parse a JSON input to create back a background material.
  75817. * @param source
  75818. * @param scene
  75819. * @param rootUrl
  75820. * @returns the instantiated BackgroundMaterial.
  75821. */
  75822. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  75823. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  75824. };
  75825. __decorate([
  75826. BABYLON.serializeAsColor3()
  75827. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  75828. __decorate([
  75829. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75830. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  75831. __decorate([
  75832. BABYLON.serialize()
  75833. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  75834. __decorate([
  75835. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75836. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  75837. __decorate([
  75838. BABYLON.serializeAsColor3()
  75839. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  75840. __decorate([
  75841. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75842. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  75843. __decorate([
  75844. BABYLON.serialize()
  75845. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  75846. __decorate([
  75847. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75848. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  75849. __decorate([
  75850. BABYLON.serializeAsColor3()
  75851. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  75852. __decorate([
  75853. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75854. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  75855. __decorate([
  75856. BABYLON.serialize()
  75857. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  75858. __decorate([
  75859. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75860. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  75861. __decorate([
  75862. BABYLON.serializeAsTexture()
  75863. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  75864. __decorate([
  75865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75866. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  75867. __decorate([
  75868. BABYLON.serialize()
  75869. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  75870. __decorate([
  75871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75872. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  75873. __decorate([
  75874. BABYLON.serializeAsTexture()
  75875. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  75876. __decorate([
  75877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75878. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  75879. __decorate([
  75880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75881. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  75882. __decorate([
  75883. BABYLON.serialize()
  75884. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  75885. __decorate([
  75886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75887. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  75888. __decorate([
  75889. BABYLON.serialize()
  75890. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  75891. __decorate([
  75892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75893. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  75894. __decorate([
  75895. BABYLON.serialize()
  75896. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  75897. __decorate([
  75898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75899. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  75900. __decorate([
  75901. BABYLON.serialize()
  75902. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  75903. __decorate([
  75904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75905. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  75906. __decorate([
  75907. BABYLON.serialize()
  75908. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  75909. __decorate([
  75910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75911. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  75912. __decorate([
  75913. BABYLON.serializeAsImageProcessingConfiguration()
  75914. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  75915. return BackgroundMaterial;
  75916. }(BABYLON.PushMaterial));
  75917. BABYLON.BackgroundMaterial = BackgroundMaterial;
  75918. })(BABYLON || (BABYLON = {}));
  75919. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  75920. BABYLON.Effect.ShadersStore['backgroundVertexShader'] = "precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";
  75921. BABYLON.Effect.ShadersStore['backgroundPixelShader'] = "#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\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 environmentColor=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;\nenvironmentColor=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){\nenvironmentColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nenvironmentColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nenvironmentColor=sampleReflection(reflectionSampler,reflectionCoords).rgb;\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentColor=toLinearSpace(environmentColor.rgb);\n#endif\n\nenvironmentColor*=vReflectionInfos.x;\n#endif\n\nvec3 groundColor=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\ngroundColor=diffuseMap.rgb;\n#endif\n\nvec3 colorBase=environmentColor*groundColor;\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#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n#ifdef OPACITYFRESNEL\n\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\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\ngl_FragColor=color;\n}";
  75922. BABYLON.Effect.IncludesShadersStore['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";
  75923. BABYLON.Effect.IncludesShadersStore['backgroundUboDeclaration'] = "layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};";
  75924. BABYLON.Effect.IncludesShadersStore['backgroundVertexDeclaration'] = "uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif";
  75925. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  75926. var BABYLON;
  75927. (function (BABYLON) {
  75928. var GLTFLoaderCoordinateSystemMode;
  75929. (function (GLTFLoaderCoordinateSystemMode) {
  75930. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  75931. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  75932. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  75933. // The glTF right-handed data is not transformed in any form and is loaded directly.
  75934. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  75935. // Sets the useRightHandedSystem flag on the scene.
  75936. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  75937. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  75938. var GLTFFileLoader = /** @class */ (function () {
  75939. function GLTFFileLoader() {
  75940. // V2 options
  75941. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  75942. this.name = "gltf";
  75943. this.extensions = {
  75944. ".gltf": { isBinary: false },
  75945. ".glb": { isBinary: true }
  75946. };
  75947. }
  75948. GLTFFileLoader.prototype.dispose = function () {
  75949. if (this._loader) {
  75950. this._loader.dispose();
  75951. }
  75952. };
  75953. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75954. try {
  75955. var loaderData = GLTFFileLoader._parse(data);
  75956. if (this.onParsed) {
  75957. this.onParsed(loaderData);
  75958. }
  75959. this._loader = this._getLoader(loaderData);
  75960. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  75961. }
  75962. catch (e) {
  75963. onError(e.message);
  75964. }
  75965. };
  75966. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  75967. try {
  75968. var loaderData = GLTFFileLoader._parse(data);
  75969. if (this.onParsed) {
  75970. this.onParsed(loaderData);
  75971. }
  75972. this._loader = this._getLoader(loaderData);
  75973. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  75974. }
  75975. catch (e) {
  75976. onError(e.message);
  75977. }
  75978. };
  75979. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  75980. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  75981. };
  75982. GLTFFileLoader._parse = function (data) {
  75983. if (data instanceof ArrayBuffer) {
  75984. return GLTFFileLoader._parseBinary(data);
  75985. }
  75986. return {
  75987. json: JSON.parse(data),
  75988. bin: null
  75989. };
  75990. };
  75991. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  75992. var loaderVersion = { major: 2, minor: 0 };
  75993. var asset = loaderData.json.asset || {};
  75994. var version = GLTFFileLoader._parseVersion(asset.version);
  75995. if (!version) {
  75996. throw new Error("Invalid version: " + asset.version);
  75997. }
  75998. if (asset.minVersion !== undefined) {
  75999. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  76000. if (!minVersion) {
  76001. throw new Error("Invalid minimum version: " + asset.minVersion);
  76002. }
  76003. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  76004. throw new Error("Incompatible minimum version: " + asset.minVersion);
  76005. }
  76006. }
  76007. var createLoaders = {
  76008. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  76009. 2: GLTFFileLoader.CreateGLTFLoaderV2
  76010. };
  76011. var createLoader = createLoaders[version.major];
  76012. if (!createLoader) {
  76013. throw new Error("Unsupported version: " + asset.version);
  76014. }
  76015. return createLoader(this);
  76016. };
  76017. GLTFFileLoader._parseBinary = function (data) {
  76018. var Binary = {
  76019. Magic: 0x46546C67
  76020. };
  76021. var binaryReader = new BinaryReader(data);
  76022. var magic = binaryReader.readUint32();
  76023. if (magic !== Binary.Magic) {
  76024. throw new Error("Unexpected magic: " + magic);
  76025. }
  76026. var version = binaryReader.readUint32();
  76027. switch (version) {
  76028. case 1: return GLTFFileLoader._parseV1(binaryReader);
  76029. case 2: return GLTFFileLoader._parseV2(binaryReader);
  76030. }
  76031. throw new Error("Unsupported version: " + version);
  76032. };
  76033. GLTFFileLoader._parseV1 = function (binaryReader) {
  76034. var ContentFormat = {
  76035. JSON: 0
  76036. };
  76037. var length = binaryReader.readUint32();
  76038. if (length != binaryReader.getLength()) {
  76039. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  76040. }
  76041. var contentLength = binaryReader.readUint32();
  76042. var contentFormat = binaryReader.readUint32();
  76043. var content;
  76044. switch (contentFormat) {
  76045. case ContentFormat.JSON: {
  76046. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  76047. break;
  76048. }
  76049. default: {
  76050. throw new Error("Unexpected content format: " + contentFormat);
  76051. }
  76052. }
  76053. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  76054. var body = binaryReader.readUint8Array(bytesRemaining);
  76055. return {
  76056. json: content,
  76057. bin: body
  76058. };
  76059. };
  76060. GLTFFileLoader._parseV2 = function (binaryReader) {
  76061. var ChunkFormat = {
  76062. JSON: 0x4E4F534A,
  76063. BIN: 0x004E4942
  76064. };
  76065. var length = binaryReader.readUint32();
  76066. if (length !== binaryReader.getLength()) {
  76067. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  76068. }
  76069. // JSON chunk
  76070. var chunkLength = binaryReader.readUint32();
  76071. var chunkFormat = binaryReader.readUint32();
  76072. if (chunkFormat !== ChunkFormat.JSON) {
  76073. throw new Error("First chunk format is not JSON");
  76074. }
  76075. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  76076. // Look for BIN chunk
  76077. var bin = null;
  76078. while (binaryReader.getPosition() < binaryReader.getLength()) {
  76079. var chunkLength_1 = binaryReader.readUint32();
  76080. var chunkFormat_1 = binaryReader.readUint32();
  76081. switch (chunkFormat_1) {
  76082. case ChunkFormat.JSON: {
  76083. throw new Error("Unexpected JSON chunk");
  76084. }
  76085. case ChunkFormat.BIN: {
  76086. bin = binaryReader.readUint8Array(chunkLength_1);
  76087. break;
  76088. }
  76089. default: {
  76090. // ignore unrecognized chunkFormat
  76091. binaryReader.skipBytes(chunkLength_1);
  76092. break;
  76093. }
  76094. }
  76095. }
  76096. return {
  76097. json: json,
  76098. bin: bin
  76099. };
  76100. };
  76101. GLTFFileLoader._parseVersion = function (version) {
  76102. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  76103. if (!match) {
  76104. return null;
  76105. }
  76106. return {
  76107. major: parseInt(match[1]),
  76108. minor: parseInt(match[2])
  76109. };
  76110. };
  76111. GLTFFileLoader._compareVersion = function (a, b) {
  76112. if (a.major > b.major)
  76113. return 1;
  76114. if (a.major < b.major)
  76115. return -1;
  76116. if (a.minor > b.minor)
  76117. return 1;
  76118. if (a.minor < b.minor)
  76119. return -1;
  76120. return 0;
  76121. };
  76122. GLTFFileLoader._decodeBufferToText = function (buffer) {
  76123. var result = "";
  76124. var length = buffer.byteLength;
  76125. for (var i = 0; i < length; i++) {
  76126. result += String.fromCharCode(buffer[i]);
  76127. }
  76128. return result;
  76129. };
  76130. // V1 options
  76131. GLTFFileLoader.HomogeneousCoordinates = false;
  76132. GLTFFileLoader.IncrementalLoading = true;
  76133. return GLTFFileLoader;
  76134. }());
  76135. BABYLON.GLTFFileLoader = GLTFFileLoader;
  76136. var BinaryReader = /** @class */ (function () {
  76137. function BinaryReader(arrayBuffer) {
  76138. this._arrayBuffer = arrayBuffer;
  76139. this._dataView = new DataView(arrayBuffer);
  76140. this._byteOffset = 0;
  76141. }
  76142. BinaryReader.prototype.getPosition = function () {
  76143. return this._byteOffset;
  76144. };
  76145. BinaryReader.prototype.getLength = function () {
  76146. return this._arrayBuffer.byteLength;
  76147. };
  76148. BinaryReader.prototype.readUint32 = function () {
  76149. var value = this._dataView.getUint32(this._byteOffset, true);
  76150. this._byteOffset += 4;
  76151. return value;
  76152. };
  76153. BinaryReader.prototype.readUint8Array = function (length) {
  76154. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  76155. this._byteOffset += length;
  76156. return value;
  76157. };
  76158. BinaryReader.prototype.skipBytes = function (length) {
  76159. this._byteOffset += length;
  76160. };
  76161. return BinaryReader;
  76162. }());
  76163. if (BABYLON.SceneLoader) {
  76164. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  76165. }
  76166. })(BABYLON || (BABYLON = {}));
  76167. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  76168. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76169. var BABYLON;
  76170. (function (BABYLON) {
  76171. var GLTF1;
  76172. (function (GLTF1) {
  76173. /**
  76174. * Enums
  76175. */
  76176. var EComponentType;
  76177. (function (EComponentType) {
  76178. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  76179. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  76180. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  76181. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  76182. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  76183. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  76184. var EShaderType;
  76185. (function (EShaderType) {
  76186. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  76187. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  76188. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  76189. var EParameterType;
  76190. (function (EParameterType) {
  76191. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  76192. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  76193. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  76194. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  76195. EParameterType[EParameterType["INT"] = 5124] = "INT";
  76196. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  76197. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  76198. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  76199. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  76200. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  76201. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  76202. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  76203. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  76204. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  76205. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  76206. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  76207. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  76208. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  76209. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  76210. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  76211. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  76212. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  76213. var ETextureWrapMode;
  76214. (function (ETextureWrapMode) {
  76215. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  76216. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  76217. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  76218. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  76219. var ETextureFilterType;
  76220. (function (ETextureFilterType) {
  76221. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  76222. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  76223. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  76224. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  76225. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  76226. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  76227. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  76228. var ETextureFormat;
  76229. (function (ETextureFormat) {
  76230. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  76231. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  76232. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  76233. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  76234. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  76235. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  76236. var ECullingType;
  76237. (function (ECullingType) {
  76238. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  76239. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  76240. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  76241. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  76242. var EBlendingFunction;
  76243. (function (EBlendingFunction) {
  76244. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  76245. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  76246. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  76247. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  76248. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  76249. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  76250. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  76251. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  76252. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  76253. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  76254. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  76255. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  76256. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  76257. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  76258. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  76259. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  76260. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  76261. })(BABYLON || (BABYLON = {}));
  76262. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  76263. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76264. var BABYLON;
  76265. (function (BABYLON) {
  76266. var GLTF1;
  76267. (function (GLTF1) {
  76268. /**
  76269. * Tokenizer. Used for shaders compatibility
  76270. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  76271. */
  76272. var ETokenType;
  76273. (function (ETokenType) {
  76274. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  76275. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  76276. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  76277. })(ETokenType || (ETokenType = {}));
  76278. var Tokenizer = /** @class */ (function () {
  76279. function Tokenizer(toParse) {
  76280. this._pos = 0;
  76281. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  76282. this._toParse = toParse;
  76283. this._maxPos = toParse.length;
  76284. }
  76285. Tokenizer.prototype.getNextToken = function () {
  76286. if (this.isEnd())
  76287. return ETokenType.END_OF_INPUT;
  76288. this.currentString = this.read();
  76289. this.currentToken = ETokenType.UNKNOWN;
  76290. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  76291. this.currentToken = ETokenType.IDENTIFIER;
  76292. this.currentIdentifier = this.currentString;
  76293. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  76294. this.currentIdentifier += this.currentString;
  76295. this.forward();
  76296. }
  76297. }
  76298. return this.currentToken;
  76299. };
  76300. Tokenizer.prototype.peek = function () {
  76301. return this._toParse[this._pos];
  76302. };
  76303. Tokenizer.prototype.read = function () {
  76304. return this._toParse[this._pos++];
  76305. };
  76306. Tokenizer.prototype.forward = function () {
  76307. this._pos++;
  76308. };
  76309. Tokenizer.prototype.isEnd = function () {
  76310. return this._pos >= this._maxPos;
  76311. };
  76312. return Tokenizer;
  76313. }());
  76314. /**
  76315. * Values
  76316. */
  76317. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  76318. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  76319. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  76320. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  76321. /**
  76322. * Parse
  76323. */
  76324. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  76325. for (var buf in parsedBuffers) {
  76326. var parsedBuffer = parsedBuffers[buf];
  76327. gltfRuntime.buffers[buf] = parsedBuffer;
  76328. gltfRuntime.buffersCount++;
  76329. }
  76330. };
  76331. var parseShaders = function (parsedShaders, gltfRuntime) {
  76332. for (var sha in parsedShaders) {
  76333. var parsedShader = parsedShaders[sha];
  76334. gltfRuntime.shaders[sha] = parsedShader;
  76335. gltfRuntime.shaderscount++;
  76336. }
  76337. };
  76338. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  76339. for (var object in parsedObjects) {
  76340. var parsedObject = parsedObjects[object];
  76341. gltfRuntime[runtimeProperty][object] = parsedObject;
  76342. }
  76343. };
  76344. /**
  76345. * Utils
  76346. */
  76347. var normalizeUVs = function (buffer) {
  76348. if (!buffer) {
  76349. return;
  76350. }
  76351. for (var i = 0; i < buffer.length / 2; i++) {
  76352. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  76353. }
  76354. };
  76355. var getAttribute = function (attributeParameter) {
  76356. if (attributeParameter.semantic === "NORMAL") {
  76357. return "normal";
  76358. }
  76359. else if (attributeParameter.semantic === "POSITION") {
  76360. return "position";
  76361. }
  76362. else if (attributeParameter.semantic === "JOINT") {
  76363. return "matricesIndices";
  76364. }
  76365. else if (attributeParameter.semantic === "WEIGHT") {
  76366. return "matricesWeights";
  76367. }
  76368. else if (attributeParameter.semantic === "COLOR") {
  76369. return "color";
  76370. }
  76371. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  76372. var channel = Number(attributeParameter.semantic.split("_")[1]);
  76373. return "uv" + (channel === 0 ? "" : channel + 1);
  76374. }
  76375. return null;
  76376. };
  76377. /**
  76378. * Loads and creates animations
  76379. */
  76380. var loadAnimations = function (gltfRuntime) {
  76381. for (var anim in gltfRuntime.animations) {
  76382. var animation = gltfRuntime.animations[anim];
  76383. if (!animation.channels || !animation.samplers) {
  76384. continue;
  76385. }
  76386. var lastAnimation = null;
  76387. for (var i = 0; i < animation.channels.length; i++) {
  76388. // Get parameters and load buffers
  76389. var channel = animation.channels[i];
  76390. var sampler = animation.samplers[channel.sampler];
  76391. if (!sampler) {
  76392. continue;
  76393. }
  76394. var inputData = null;
  76395. var outputData = null;
  76396. if (animation.parameters) {
  76397. inputData = animation.parameters[sampler.input];
  76398. outputData = animation.parameters[sampler.output];
  76399. }
  76400. else {
  76401. inputData = sampler.input;
  76402. outputData = sampler.output;
  76403. }
  76404. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  76405. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  76406. var targetID = channel.target.id;
  76407. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  76408. if (targetNode === null) {
  76409. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  76410. }
  76411. if (targetNode === null) {
  76412. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  76413. continue;
  76414. }
  76415. var isBone = targetNode instanceof BABYLON.Bone;
  76416. // Get target path (position, rotation or scaling)
  76417. var targetPath = channel.target.path;
  76418. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  76419. if (targetPathIndex !== -1) {
  76420. targetPath = babylonAnimationPaths[targetPathIndex];
  76421. }
  76422. // Determine animation type
  76423. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  76424. if (!isBone) {
  76425. if (targetPath === "rotationQuaternion") {
  76426. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  76427. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  76428. }
  76429. else {
  76430. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  76431. }
  76432. }
  76433. // Create animation and key frames
  76434. var babylonAnimation = null;
  76435. var keys = [];
  76436. var arrayOffset = 0;
  76437. var modifyKey = false;
  76438. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  76439. babylonAnimation = lastAnimation;
  76440. modifyKey = true;
  76441. }
  76442. if (!modifyKey) {
  76443. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  76444. }
  76445. // For each frame
  76446. for (var j = 0; j < bufferInput.length; j++) {
  76447. var value = null;
  76448. if (targetPath === "rotationQuaternion") {
  76449. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  76450. arrayOffset += 4;
  76451. }
  76452. else {
  76453. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  76454. arrayOffset += 3;
  76455. }
  76456. if (isBone) {
  76457. var bone = targetNode;
  76458. var translation = BABYLON.Vector3.Zero();
  76459. var rotationQuaternion = new BABYLON.Quaternion();
  76460. var scaling = BABYLON.Vector3.Zero();
  76461. // Warning on decompose
  76462. var mat = bone.getBaseMatrix();
  76463. if (modifyKey && lastAnimation) {
  76464. mat = lastAnimation.getKeys()[j].value;
  76465. }
  76466. mat.decompose(scaling, rotationQuaternion, translation);
  76467. if (targetPath === "position") {
  76468. translation = value;
  76469. }
  76470. else if (targetPath === "rotationQuaternion") {
  76471. rotationQuaternion = value;
  76472. }
  76473. else {
  76474. scaling = value;
  76475. }
  76476. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  76477. }
  76478. if (!modifyKey) {
  76479. keys.push({
  76480. frame: bufferInput[j],
  76481. value: value
  76482. });
  76483. }
  76484. else if (lastAnimation) {
  76485. lastAnimation.getKeys()[j].value = value;
  76486. }
  76487. }
  76488. // Finish
  76489. if (!modifyKey && babylonAnimation) {
  76490. babylonAnimation.setKeys(keys);
  76491. targetNode.animations.push(babylonAnimation);
  76492. }
  76493. lastAnimation = babylonAnimation;
  76494. gltfRuntime.scene.stopAnimation(targetNode);
  76495. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  76496. }
  76497. }
  76498. };
  76499. /**
  76500. * Returns the bones transformation matrix
  76501. */
  76502. var configureBoneTransformation = function (node) {
  76503. var mat = null;
  76504. if (node.translation || node.rotation || node.scale) {
  76505. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  76506. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  76507. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  76508. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  76509. }
  76510. else {
  76511. mat = BABYLON.Matrix.FromArray(node.matrix);
  76512. }
  76513. return mat;
  76514. };
  76515. /**
  76516. * Returns the parent bone
  76517. */
  76518. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  76519. // Try to find
  76520. for (var i = 0; i < newSkeleton.bones.length; i++) {
  76521. if (newSkeleton.bones[i].name === jointName) {
  76522. return newSkeleton.bones[i];
  76523. }
  76524. }
  76525. // Not found, search in gltf nodes
  76526. var nodes = gltfRuntime.nodes;
  76527. for (var nde in nodes) {
  76528. var node = nodes[nde];
  76529. if (!node.jointName) {
  76530. continue;
  76531. }
  76532. var children = node.children;
  76533. for (var i = 0; i < children.length; i++) {
  76534. var child = gltfRuntime.nodes[children[i]];
  76535. if (!child.jointName) {
  76536. continue;
  76537. }
  76538. if (child.jointName === jointName) {
  76539. var mat = configureBoneTransformation(node);
  76540. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  76541. bone.id = nde;
  76542. return bone;
  76543. }
  76544. }
  76545. }
  76546. return null;
  76547. };
  76548. /**
  76549. * Returns the appropriate root node
  76550. */
  76551. var getNodeToRoot = function (nodesToRoot, id) {
  76552. for (var i = 0; i < nodesToRoot.length; i++) {
  76553. var nodeToRoot = nodesToRoot[i];
  76554. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  76555. var child = nodeToRoot.node.children[j];
  76556. if (child === id) {
  76557. return nodeToRoot.bone;
  76558. }
  76559. }
  76560. }
  76561. return null;
  76562. };
  76563. /**
  76564. * Returns the node with the joint name
  76565. */
  76566. var getJointNode = function (gltfRuntime, jointName) {
  76567. var nodes = gltfRuntime.nodes;
  76568. var node = nodes[jointName];
  76569. if (node) {
  76570. return {
  76571. node: node,
  76572. id: jointName
  76573. };
  76574. }
  76575. for (var nde in nodes) {
  76576. node = nodes[nde];
  76577. if (node.jointName === jointName) {
  76578. return {
  76579. node: node,
  76580. id: nde
  76581. };
  76582. }
  76583. }
  76584. return null;
  76585. };
  76586. /**
  76587. * Checks if a nodes is in joints
  76588. */
  76589. var nodeIsInJoints = function (skins, id) {
  76590. for (var i = 0; i < skins.jointNames.length; i++) {
  76591. if (skins.jointNames[i] === id) {
  76592. return true;
  76593. }
  76594. }
  76595. return false;
  76596. };
  76597. /**
  76598. * Fills the nodes to root for bones and builds hierarchy
  76599. */
  76600. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  76601. // Creates nodes for root
  76602. for (var nde in gltfRuntime.nodes) {
  76603. var node = gltfRuntime.nodes[nde];
  76604. var id = nde;
  76605. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  76606. continue;
  76607. }
  76608. // Create node to root bone
  76609. var mat = configureBoneTransformation(node);
  76610. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  76611. bone.id = id;
  76612. nodesToRoot.push({ bone: bone, node: node, id: id });
  76613. }
  76614. // Parenting
  76615. for (var i = 0; i < nodesToRoot.length; i++) {
  76616. var nodeToRoot = nodesToRoot[i];
  76617. var children = nodeToRoot.node.children;
  76618. for (var j = 0; j < children.length; j++) {
  76619. var child = null;
  76620. for (var k = 0; k < nodesToRoot.length; k++) {
  76621. if (nodesToRoot[k].id === children[j]) {
  76622. child = nodesToRoot[k];
  76623. break;
  76624. }
  76625. }
  76626. if (child) {
  76627. child.bone._parent = nodeToRoot.bone;
  76628. nodeToRoot.bone.children.push(child.bone);
  76629. }
  76630. }
  76631. }
  76632. };
  76633. /**
  76634. * Imports a skeleton
  76635. */
  76636. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  76637. if (!newSkeleton) {
  76638. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  76639. }
  76640. if (!skins.babylonSkeleton) {
  76641. return newSkeleton;
  76642. }
  76643. // Find the root bones
  76644. var nodesToRoot = [];
  76645. var nodesToRootToAdd = [];
  76646. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  76647. newSkeleton.bones = [];
  76648. // Joints
  76649. for (var i = 0; i < skins.jointNames.length; i++) {
  76650. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76651. if (!jointNode) {
  76652. continue;
  76653. }
  76654. var node = jointNode.node;
  76655. if (!node) {
  76656. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  76657. continue;
  76658. }
  76659. var id = jointNode.id;
  76660. // Optimize, if the bone already exists...
  76661. var existingBone = gltfRuntime.scene.getBoneByID(id);
  76662. if (existingBone) {
  76663. newSkeleton.bones.push(existingBone);
  76664. continue;
  76665. }
  76666. // Search for parent bone
  76667. var foundBone = false;
  76668. var parentBone = null;
  76669. for (var j = 0; j < i; j++) {
  76670. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  76671. if (!jointNode_1) {
  76672. continue;
  76673. }
  76674. var joint = jointNode_1.node;
  76675. if (!joint) {
  76676. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  76677. continue;
  76678. }
  76679. var children = joint.children;
  76680. if (!children) {
  76681. continue;
  76682. }
  76683. foundBone = false;
  76684. for (var k = 0; k < children.length; k++) {
  76685. if (children[k] === id) {
  76686. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  76687. foundBone = true;
  76688. break;
  76689. }
  76690. }
  76691. if (foundBone) {
  76692. break;
  76693. }
  76694. }
  76695. // Create bone
  76696. var mat = configureBoneTransformation(node);
  76697. if (!parentBone && nodesToRoot.length > 0) {
  76698. parentBone = getNodeToRoot(nodesToRoot, id);
  76699. if (parentBone) {
  76700. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  76701. nodesToRootToAdd.push(parentBone);
  76702. }
  76703. }
  76704. }
  76705. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  76706. bone.id = id;
  76707. }
  76708. // Polish
  76709. var bones = newSkeleton.bones;
  76710. newSkeleton.bones = [];
  76711. for (var i = 0; i < skins.jointNames.length; i++) {
  76712. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76713. if (!jointNode) {
  76714. continue;
  76715. }
  76716. for (var j = 0; j < bones.length; j++) {
  76717. if (bones[j].id === jointNode.id) {
  76718. newSkeleton.bones.push(bones[j]);
  76719. break;
  76720. }
  76721. }
  76722. }
  76723. newSkeleton.prepare();
  76724. // Finish
  76725. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  76726. newSkeleton.bones.push(nodesToRootToAdd[i]);
  76727. }
  76728. return newSkeleton;
  76729. };
  76730. /**
  76731. * Imports a mesh and its geometries
  76732. */
  76733. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  76734. if (!newMesh) {
  76735. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  76736. newMesh.id = id;
  76737. }
  76738. if (!node.babylonNode) {
  76739. return newMesh;
  76740. }
  76741. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  76742. if (!newMesh.material) {
  76743. newMesh.material = multiMat;
  76744. }
  76745. var vertexData = new BABYLON.VertexData();
  76746. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  76747. var verticesStarts = new Array();
  76748. var verticesCounts = new Array();
  76749. var indexStarts = new Array();
  76750. var indexCounts = new Array();
  76751. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76752. var meshID = meshes[meshIndex];
  76753. var mesh = gltfRuntime.meshes[meshID];
  76754. if (!mesh) {
  76755. continue;
  76756. }
  76757. // Positions, normals and UVs
  76758. for (var i = 0; i < mesh.primitives.length; i++) {
  76759. // Temporary vertex data
  76760. var tempVertexData = new BABYLON.VertexData();
  76761. var primitive = mesh.primitives[i];
  76762. if (primitive.mode !== 4) {
  76763. // continue;
  76764. }
  76765. var attributes = primitive.attributes;
  76766. var accessor = null;
  76767. var buffer = null;
  76768. // Set positions, normal and uvs
  76769. for (var semantic in attributes) {
  76770. // Link accessor and buffer view
  76771. accessor = gltfRuntime.accessors[attributes[semantic]];
  76772. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76773. if (semantic === "NORMAL") {
  76774. tempVertexData.normals = new Float32Array(buffer.length);
  76775. tempVertexData.normals.set(buffer);
  76776. }
  76777. else if (semantic === "POSITION") {
  76778. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  76779. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  76780. for (var j = 0; j < buffer.length; j += 4) {
  76781. tempVertexData.positions[j] = buffer[j];
  76782. tempVertexData.positions[j + 1] = buffer[j + 1];
  76783. tempVertexData.positions[j + 2] = buffer[j + 2];
  76784. }
  76785. }
  76786. else {
  76787. tempVertexData.positions = new Float32Array(buffer.length);
  76788. tempVertexData.positions.set(buffer);
  76789. }
  76790. verticesCounts.push(tempVertexData.positions.length);
  76791. }
  76792. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  76793. var channel = Number(semantic.split("_")[1]);
  76794. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  76795. var uvs = new Float32Array(buffer.length);
  76796. uvs.set(buffer);
  76797. normalizeUVs(uvs);
  76798. tempVertexData.set(uvs, uvKind);
  76799. }
  76800. else if (semantic === "JOINT") {
  76801. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  76802. tempVertexData.matricesIndices.set(buffer);
  76803. }
  76804. else if (semantic === "WEIGHT") {
  76805. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  76806. tempVertexData.matricesWeights.set(buffer);
  76807. }
  76808. else if (semantic === "COLOR") {
  76809. tempVertexData.colors = new Float32Array(buffer.length);
  76810. tempVertexData.colors.set(buffer);
  76811. }
  76812. }
  76813. // Indices
  76814. accessor = gltfRuntime.accessors[primitive.indices];
  76815. if (accessor) {
  76816. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76817. tempVertexData.indices = new Int32Array(buffer.length);
  76818. tempVertexData.indices.set(buffer);
  76819. indexCounts.push(tempVertexData.indices.length);
  76820. }
  76821. else {
  76822. // Set indices on the fly
  76823. var indices = [];
  76824. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  76825. indices.push(j);
  76826. }
  76827. tempVertexData.indices = new Int32Array(indices);
  76828. indexCounts.push(tempVertexData.indices.length);
  76829. }
  76830. vertexData.merge(tempVertexData);
  76831. // Sub material
  76832. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  76833. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  76834. // Update vertices start and index start
  76835. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  76836. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  76837. }
  76838. }
  76839. // Apply geometry
  76840. geometry.setAllVerticesData(vertexData, false);
  76841. newMesh.computeWorldMatrix(true);
  76842. // Apply submeshes
  76843. newMesh.subMeshes = [];
  76844. var index = 0;
  76845. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76846. var meshID = meshes[meshIndex];
  76847. var mesh = gltfRuntime.meshes[meshID];
  76848. if (!mesh) {
  76849. continue;
  76850. }
  76851. for (var i = 0; i < mesh.primitives.length; i++) {
  76852. if (mesh.primitives[i].mode !== 4) {
  76853. //continue;
  76854. }
  76855. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  76856. index++;
  76857. }
  76858. }
  76859. // Finish
  76860. return newMesh;
  76861. };
  76862. /**
  76863. * Configure node transformation from position, rotation and scaling
  76864. */
  76865. var configureNode = function (newNode, position, rotation, scaling) {
  76866. if (newNode.position) {
  76867. newNode.position = position;
  76868. }
  76869. if (newNode.rotationQuaternion || newNode.rotation) {
  76870. newNode.rotationQuaternion = rotation;
  76871. }
  76872. if (newNode.scaling) {
  76873. newNode.scaling = scaling;
  76874. }
  76875. };
  76876. /**
  76877. * Configures node from transformation matrix
  76878. */
  76879. var configureNodeFromMatrix = function (newNode, node, parent) {
  76880. if (node.matrix) {
  76881. var position = new BABYLON.Vector3(0, 0, 0);
  76882. var rotation = new BABYLON.Quaternion();
  76883. var scaling = new BABYLON.Vector3(0, 0, 0);
  76884. var mat = BABYLON.Matrix.FromArray(node.matrix);
  76885. mat.decompose(scaling, rotation, position);
  76886. configureNode(newNode, position, rotation, scaling);
  76887. }
  76888. else if (node.translation && node.rotation && node.scale) {
  76889. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  76890. }
  76891. newNode.computeWorldMatrix(true);
  76892. };
  76893. /**
  76894. * Imports a node
  76895. */
  76896. var importNode = function (gltfRuntime, node, id, parent) {
  76897. var lastNode = null;
  76898. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  76899. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  76900. return null;
  76901. }
  76902. }
  76903. // Meshes
  76904. if (node.skin) {
  76905. if (node.meshes) {
  76906. var skin = gltfRuntime.skins[node.skin];
  76907. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  76908. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  76909. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  76910. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  76911. if (!skin.babylonSkeleton) {
  76912. skin.babylonSkeleton = newMesh.skeleton;
  76913. }
  76914. }
  76915. lastNode = newMesh;
  76916. }
  76917. }
  76918. else if (node.meshes) {
  76919. /**
  76920. * Improve meshes property
  76921. */
  76922. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  76923. lastNode = newMesh;
  76924. }
  76925. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  76926. var light = gltfRuntime.lights[node.light];
  76927. if (light) {
  76928. if (light.type === "ambient") {
  76929. var ambienLight = light[light.type];
  76930. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76931. hemiLight.name = node.name || "";
  76932. if (ambienLight.color) {
  76933. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  76934. }
  76935. lastNode = hemiLight;
  76936. }
  76937. else if (light.type === "directional") {
  76938. var directionalLight = light[light.type];
  76939. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76940. dirLight.name = node.name || "";
  76941. if (directionalLight.color) {
  76942. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  76943. }
  76944. lastNode = dirLight;
  76945. }
  76946. else if (light.type === "point") {
  76947. var pointLight = light[light.type];
  76948. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76949. ptLight.name = node.name || "";
  76950. if (pointLight.color) {
  76951. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  76952. }
  76953. lastNode = ptLight;
  76954. }
  76955. else if (light.type === "spot") {
  76956. var spotLight = light[light.type];
  76957. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  76958. spLight.name = node.name || "";
  76959. if (spotLight.color) {
  76960. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  76961. }
  76962. if (spotLight.fallOfAngle) {
  76963. spLight.angle = spotLight.fallOfAngle;
  76964. }
  76965. if (spotLight.fallOffExponent) {
  76966. spLight.exponent = spotLight.fallOffExponent;
  76967. }
  76968. lastNode = spLight;
  76969. }
  76970. }
  76971. }
  76972. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  76973. var camera = gltfRuntime.cameras[node.camera];
  76974. if (camera) {
  76975. if (camera.type === "orthographic") {
  76976. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76977. orthoCamera.name = node.name || "";
  76978. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  76979. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  76980. lastNode = orthoCamera;
  76981. }
  76982. else if (camera.type === "perspective") {
  76983. var perspectiveCamera = camera[camera.type];
  76984. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76985. persCamera.name = node.name || "";
  76986. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  76987. if (!perspectiveCamera.aspectRatio) {
  76988. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  76989. }
  76990. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  76991. persCamera.maxZ = perspectiveCamera.zfar;
  76992. persCamera.minZ = perspectiveCamera.znear;
  76993. }
  76994. lastNode = persCamera;
  76995. }
  76996. }
  76997. }
  76998. // Empty node
  76999. if (!node.jointName) {
  77000. if (node.babylonNode) {
  77001. return node.babylonNode;
  77002. }
  77003. else if (lastNode === null) {
  77004. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  77005. node.babylonNode = dummy;
  77006. lastNode = dummy;
  77007. }
  77008. }
  77009. if (lastNode !== null) {
  77010. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  77011. configureNodeFromMatrix(lastNode, node, parent);
  77012. }
  77013. else {
  77014. var translation = node.translation || [0, 0, 0];
  77015. var rotation = node.rotation || [0, 0, 0, 1];
  77016. var scale = node.scale || [1, 1, 1];
  77017. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  77018. }
  77019. lastNode.updateCache(true);
  77020. node.babylonNode = lastNode;
  77021. }
  77022. return lastNode;
  77023. };
  77024. /**
  77025. * Traverses nodes and creates them
  77026. */
  77027. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  77028. if (meshIncluded === void 0) { meshIncluded = false; }
  77029. var node = gltfRuntime.nodes[id];
  77030. var newNode = null;
  77031. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  77032. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  77033. meshIncluded = true;
  77034. }
  77035. else {
  77036. meshIncluded = false;
  77037. }
  77038. }
  77039. else {
  77040. meshIncluded = true;
  77041. }
  77042. if (!node.jointName && meshIncluded) {
  77043. newNode = importNode(gltfRuntime, node, id, parent);
  77044. if (newNode !== null) {
  77045. newNode.id = id;
  77046. newNode.parent = parent;
  77047. }
  77048. }
  77049. if (node.children) {
  77050. for (var i = 0; i < node.children.length; i++) {
  77051. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  77052. }
  77053. }
  77054. };
  77055. /**
  77056. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  77057. */
  77058. var postLoad = function (gltfRuntime) {
  77059. // Nodes
  77060. var currentScene = gltfRuntime.currentScene;
  77061. if (currentScene) {
  77062. for (var i = 0; i < currentScene.nodes.length; i++) {
  77063. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77064. }
  77065. }
  77066. else {
  77067. for (var thing in gltfRuntime.scenes) {
  77068. currentScene = gltfRuntime.scenes[thing];
  77069. for (var i = 0; i < currentScene.nodes.length; i++) {
  77070. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77071. }
  77072. }
  77073. }
  77074. // Set animations
  77075. loadAnimations(gltfRuntime);
  77076. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  77077. var skeleton = gltfRuntime.scene.skeletons[i];
  77078. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  77079. }
  77080. };
  77081. /**
  77082. * onBind shaderrs callback to set uniforms and matrices
  77083. */
  77084. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  77085. var materialValues = material.values || technique.parameters;
  77086. for (var unif in unTreatedUniforms) {
  77087. var uniform = unTreatedUniforms[unif];
  77088. var type = uniform.type;
  77089. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  77090. if (uniform.semantic && !uniform.source && !uniform.node) {
  77091. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  77092. }
  77093. else if (uniform.semantic && (uniform.source || uniform.node)) {
  77094. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  77095. if (source === null) {
  77096. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  77097. }
  77098. if (source === null) {
  77099. continue;
  77100. }
  77101. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  77102. }
  77103. }
  77104. else {
  77105. var value = materialValues[technique.uniforms[unif]];
  77106. if (!value) {
  77107. continue;
  77108. }
  77109. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  77110. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  77111. if (texture === null || texture === undefined) {
  77112. continue;
  77113. }
  77114. shaderMaterial.getEffect().setTexture(unif, texture);
  77115. }
  77116. else {
  77117. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  77118. }
  77119. }
  77120. }
  77121. onSuccess(shaderMaterial);
  77122. };
  77123. /**
  77124. * Prepare uniforms to send the only one time
  77125. * Loads the appropriate textures
  77126. */
  77127. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  77128. var materialValues = material.values || technique.parameters;
  77129. var techniqueUniforms = technique.uniforms;
  77130. /**
  77131. * Prepare values here (not matrices)
  77132. */
  77133. for (var unif in unTreatedUniforms) {
  77134. var uniform = unTreatedUniforms[unif];
  77135. var type = uniform.type;
  77136. var value = materialValues[techniqueUniforms[unif]];
  77137. if (value === undefined) {
  77138. // In case the value is the same for all materials
  77139. value = uniform.value;
  77140. }
  77141. if (!value) {
  77142. continue;
  77143. }
  77144. var onLoadTexture = function (uniformName) {
  77145. return function (texture) {
  77146. if (uniform.value && uniformName) {
  77147. // Static uniform
  77148. shaderMaterial.setTexture(uniformName, texture);
  77149. delete unTreatedUniforms[uniformName];
  77150. }
  77151. };
  77152. };
  77153. // Texture (sampler2D)
  77154. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  77155. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  77156. }
  77157. else {
  77158. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  77159. // Static uniform
  77160. delete unTreatedUniforms[unif];
  77161. }
  77162. }
  77163. }
  77164. };
  77165. /**
  77166. * Shader compilation failed
  77167. */
  77168. var onShaderCompileError = function (program, shaderMaterial, onError) {
  77169. return function (effect, error) {
  77170. shaderMaterial.dispose(true);
  77171. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  77172. };
  77173. };
  77174. /**
  77175. * Shader compilation success
  77176. */
  77177. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  77178. return function (_) {
  77179. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  77180. shaderMaterial.onBind = function (mesh) {
  77181. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  77182. };
  77183. };
  77184. };
  77185. /**
  77186. * Returns the appropriate uniform if already handled by babylon
  77187. */
  77188. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  77189. for (var unif in technique.uniforms) {
  77190. var uniform = technique.uniforms[unif];
  77191. var uniformParameter = technique.parameters[uniform];
  77192. if (tokenizer.currentIdentifier === unif) {
  77193. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  77194. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  77195. if (transformIndex !== -1) {
  77196. delete unTreatedUniforms[unif];
  77197. return babylonTransforms[transformIndex];
  77198. }
  77199. }
  77200. }
  77201. }
  77202. return tokenizer.currentIdentifier;
  77203. };
  77204. /**
  77205. * All shaders loaded. Create materials one by one
  77206. */
  77207. var importMaterials = function (gltfRuntime) {
  77208. // Create materials
  77209. for (var mat in gltfRuntime.materials) {
  77210. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  77211. }
  77212. };
  77213. /**
  77214. * Implementation of the base glTF spec
  77215. */
  77216. var GLTFLoaderBase = /** @class */ (function () {
  77217. function GLTFLoaderBase() {
  77218. }
  77219. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  77220. var gltfRuntime = {
  77221. extensions: {},
  77222. accessors: {},
  77223. buffers: {},
  77224. bufferViews: {},
  77225. meshes: {},
  77226. lights: {},
  77227. cameras: {},
  77228. nodes: {},
  77229. images: {},
  77230. textures: {},
  77231. shaders: {},
  77232. programs: {},
  77233. samplers: {},
  77234. techniques: {},
  77235. materials: {},
  77236. animations: {},
  77237. skins: {},
  77238. extensionsUsed: [],
  77239. scenes: {},
  77240. buffersCount: 0,
  77241. shaderscount: 0,
  77242. scene: scene,
  77243. rootUrl: rootUrl,
  77244. loadedBufferCount: 0,
  77245. loadedBufferViews: {},
  77246. loadedShaderCount: 0,
  77247. importOnlyMeshes: false,
  77248. dummyNodes: []
  77249. };
  77250. // Parse
  77251. if (parsedData.extensions) {
  77252. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  77253. }
  77254. if (parsedData.extensionsUsed) {
  77255. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  77256. }
  77257. if (parsedData.buffers) {
  77258. parseBuffers(parsedData.buffers, gltfRuntime);
  77259. }
  77260. if (parsedData.bufferViews) {
  77261. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  77262. }
  77263. if (parsedData.accessors) {
  77264. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  77265. }
  77266. if (parsedData.meshes) {
  77267. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  77268. }
  77269. if (parsedData.lights) {
  77270. parseObject(parsedData.lights, "lights", gltfRuntime);
  77271. }
  77272. if (parsedData.cameras) {
  77273. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  77274. }
  77275. if (parsedData.nodes) {
  77276. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  77277. }
  77278. if (parsedData.images) {
  77279. parseObject(parsedData.images, "images", gltfRuntime);
  77280. }
  77281. if (parsedData.textures) {
  77282. parseObject(parsedData.textures, "textures", gltfRuntime);
  77283. }
  77284. if (parsedData.shaders) {
  77285. parseShaders(parsedData.shaders, gltfRuntime);
  77286. }
  77287. if (parsedData.programs) {
  77288. parseObject(parsedData.programs, "programs", gltfRuntime);
  77289. }
  77290. if (parsedData.samplers) {
  77291. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  77292. }
  77293. if (parsedData.techniques) {
  77294. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  77295. }
  77296. if (parsedData.materials) {
  77297. parseObject(parsedData.materials, "materials", gltfRuntime);
  77298. }
  77299. if (parsedData.animations) {
  77300. parseObject(parsedData.animations, "animations", gltfRuntime);
  77301. }
  77302. if (parsedData.skins) {
  77303. parseObject(parsedData.skins, "skins", gltfRuntime);
  77304. }
  77305. if (parsedData.scenes) {
  77306. gltfRuntime.scenes = parsedData.scenes;
  77307. }
  77308. if (parsedData.scene && parsedData.scenes) {
  77309. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  77310. }
  77311. return gltfRuntime;
  77312. };
  77313. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77314. var buffer = gltfRuntime.buffers[id];
  77315. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  77316. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  77317. }
  77318. else {
  77319. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  77320. if (request) {
  77321. onError(request.status + " " + request.statusText);
  77322. }
  77323. });
  77324. }
  77325. };
  77326. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77327. var texture = gltfRuntime.textures[id];
  77328. if (!texture || !texture.source) {
  77329. onError("");
  77330. return;
  77331. }
  77332. if (texture.babylonTexture) {
  77333. onSuccess(null);
  77334. return;
  77335. }
  77336. var source = gltfRuntime.images[texture.source];
  77337. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  77338. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  77339. }
  77340. else {
  77341. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  77342. if (request) {
  77343. onError(request.status + " " + request.statusText);
  77344. }
  77345. });
  77346. }
  77347. };
  77348. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77349. var texture = gltfRuntime.textures[id];
  77350. if (texture.babylonTexture) {
  77351. onSuccess(texture.babylonTexture);
  77352. return;
  77353. }
  77354. var sampler = gltfRuntime.samplers[texture.sampler];
  77355. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  77356. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  77357. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  77358. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  77359. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  77360. var blob = new Blob([buffer]);
  77361. var blobURL = URL.createObjectURL(blob);
  77362. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  77363. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  77364. if (sampler.wrapS !== undefined) {
  77365. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  77366. }
  77367. if (sampler.wrapT !== undefined) {
  77368. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  77369. }
  77370. newTexture.name = id;
  77371. texture.babylonTexture = newTexture;
  77372. onSuccess(newTexture);
  77373. };
  77374. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77375. var shader = gltfRuntime.shaders[id];
  77376. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  77377. var shaderString = atob(shader.uri.split(",")[1]);
  77378. onSuccess(shaderString);
  77379. }
  77380. else {
  77381. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  77382. if (request) {
  77383. onError(request.status + " " + request.statusText);
  77384. }
  77385. });
  77386. }
  77387. };
  77388. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77389. var material = gltfRuntime.materials[id];
  77390. if (!material.technique) {
  77391. if (onError) {
  77392. onError("No technique found.");
  77393. }
  77394. return;
  77395. }
  77396. var technique = gltfRuntime.techniques[material.technique];
  77397. if (!technique) {
  77398. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  77399. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  77400. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77401. onSuccess(defaultMaterial);
  77402. return;
  77403. }
  77404. var program = gltfRuntime.programs[technique.program];
  77405. var states = technique.states;
  77406. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  77407. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  77408. var newVertexShader = "";
  77409. var newPixelShader = "";
  77410. var vertexTokenizer = new Tokenizer(vertexShader);
  77411. var pixelTokenizer = new Tokenizer(pixelShader);
  77412. var unTreatedUniforms = {};
  77413. var uniforms = [];
  77414. var attributes = [];
  77415. var samplers = [];
  77416. // Fill uniform, sampler2D and attributes
  77417. for (var unif in technique.uniforms) {
  77418. var uniform = technique.uniforms[unif];
  77419. var uniformParameter = technique.parameters[uniform];
  77420. unTreatedUniforms[unif] = uniformParameter;
  77421. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  77422. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  77423. if (transformIndex !== -1) {
  77424. uniforms.push(babylonTransforms[transformIndex]);
  77425. delete unTreatedUniforms[unif];
  77426. }
  77427. else {
  77428. uniforms.push(unif);
  77429. }
  77430. }
  77431. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  77432. samplers.push(unif);
  77433. }
  77434. else {
  77435. uniforms.push(unif);
  77436. }
  77437. }
  77438. for (var attr in technique.attributes) {
  77439. var attribute = technique.attributes[attr];
  77440. var attributeParameter = technique.parameters[attribute];
  77441. if (attributeParameter.semantic) {
  77442. attributes.push(getAttribute(attributeParameter));
  77443. }
  77444. }
  77445. // Configure vertex shader
  77446. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  77447. var tokenType = vertexTokenizer.currentToken;
  77448. if (tokenType !== ETokenType.IDENTIFIER) {
  77449. newVertexShader += vertexTokenizer.currentString;
  77450. continue;
  77451. }
  77452. var foundAttribute = false;
  77453. for (var attr in technique.attributes) {
  77454. var attribute = technique.attributes[attr];
  77455. var attributeParameter = technique.parameters[attribute];
  77456. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  77457. newVertexShader += getAttribute(attributeParameter);
  77458. foundAttribute = true;
  77459. break;
  77460. }
  77461. }
  77462. if (foundAttribute) {
  77463. continue;
  77464. }
  77465. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  77466. }
  77467. // Configure pixel shader
  77468. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  77469. var tokenType = pixelTokenizer.currentToken;
  77470. if (tokenType !== ETokenType.IDENTIFIER) {
  77471. newPixelShader += pixelTokenizer.currentString;
  77472. continue;
  77473. }
  77474. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  77475. }
  77476. // Create shader material
  77477. var shaderPath = {
  77478. vertex: program.vertexShader + id,
  77479. fragment: program.fragmentShader + id
  77480. };
  77481. var options = {
  77482. attributes: attributes,
  77483. uniforms: uniforms,
  77484. samplers: samplers,
  77485. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  77486. };
  77487. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  77488. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  77489. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  77490. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  77491. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  77492. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77493. if (states && states.functions) {
  77494. var functions = states.functions;
  77495. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  77496. shaderMaterial.backFaceCulling = false;
  77497. }
  77498. var blendFunc = functions.blendFuncSeparate;
  77499. if (blendFunc) {
  77500. 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) {
  77501. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  77502. }
  77503. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77504. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  77505. }
  77506. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77507. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  77508. }
  77509. 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) {
  77510. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  77511. }
  77512. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77513. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  77514. }
  77515. 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) {
  77516. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  77517. }
  77518. }
  77519. }
  77520. };
  77521. return GLTFLoaderBase;
  77522. }());
  77523. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  77524. /**
  77525. * glTF V1 Loader
  77526. */
  77527. var GLTFLoader = /** @class */ (function () {
  77528. function GLTFLoader() {
  77529. }
  77530. GLTFLoader.RegisterExtension = function (extension) {
  77531. if (GLTFLoader.Extensions[extension.name]) {
  77532. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  77533. return;
  77534. }
  77535. GLTFLoader.Extensions[extension.name] = extension;
  77536. };
  77537. GLTFLoader.prototype.dispose = function () {
  77538. // do nothing
  77539. };
  77540. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77541. var _this = this;
  77542. scene.useRightHandedSystem = true;
  77543. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77544. gltfRuntime.importOnlyMeshes = true;
  77545. if (meshesNames === "") {
  77546. gltfRuntime.importMeshesNames = [];
  77547. }
  77548. else if (typeof meshesNames === "string") {
  77549. gltfRuntime.importMeshesNames = [meshesNames];
  77550. }
  77551. else if (meshesNames && !(meshesNames instanceof Array)) {
  77552. gltfRuntime.importMeshesNames = [meshesNames];
  77553. }
  77554. else {
  77555. gltfRuntime.importMeshesNames = [];
  77556. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  77557. }
  77558. // Create nodes
  77559. _this._createNodes(gltfRuntime);
  77560. var meshes = new Array();
  77561. var skeletons = new Array();
  77562. // Fill arrays of meshes and skeletons
  77563. for (var nde in gltfRuntime.nodes) {
  77564. var node = gltfRuntime.nodes[nde];
  77565. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  77566. meshes.push(node.babylonNode);
  77567. }
  77568. }
  77569. for (var skl in gltfRuntime.skins) {
  77570. var skin = gltfRuntime.skins[skl];
  77571. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  77572. skeletons.push(skin.babylonSkeleton);
  77573. }
  77574. }
  77575. // Load buffers, shaders, materials, etc.
  77576. _this._loadBuffersAsync(gltfRuntime, function () {
  77577. _this._loadShadersAsync(gltfRuntime, function () {
  77578. importMaterials(gltfRuntime);
  77579. postLoad(gltfRuntime);
  77580. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77581. onSuccess(meshes, [], skeletons);
  77582. }
  77583. });
  77584. }, onProgress);
  77585. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77586. onSuccess(meshes, [], skeletons);
  77587. }
  77588. }, onError);
  77589. return true;
  77590. };
  77591. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  77592. var _this = this;
  77593. scene.useRightHandedSystem = true;
  77594. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77595. // Load runtime extensios
  77596. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  77597. // Create nodes
  77598. _this._createNodes(gltfRuntime);
  77599. // Load buffers, shaders, materials, etc.
  77600. _this._loadBuffersAsync(gltfRuntime, function () {
  77601. _this._loadShadersAsync(gltfRuntime, function () {
  77602. importMaterials(gltfRuntime);
  77603. postLoad(gltfRuntime);
  77604. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  77605. onSuccess();
  77606. }
  77607. });
  77608. });
  77609. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  77610. onSuccess();
  77611. }
  77612. }, onError);
  77613. }, onError);
  77614. };
  77615. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  77616. var hasShaders = false;
  77617. var processShader = function (sha, shader) {
  77618. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  77619. gltfRuntime.loadedShaderCount++;
  77620. if (shaderString) {
  77621. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  77622. }
  77623. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  77624. onload();
  77625. }
  77626. }, function () {
  77627. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  77628. });
  77629. };
  77630. for (var sha in gltfRuntime.shaders) {
  77631. hasShaders = true;
  77632. var shader = gltfRuntime.shaders[sha];
  77633. if (shader) {
  77634. processShader.bind(this, sha, shader)();
  77635. }
  77636. else {
  77637. BABYLON.Tools.Error("No shader named: " + sha);
  77638. }
  77639. }
  77640. if (!hasShaders) {
  77641. onload();
  77642. }
  77643. };
  77644. ;
  77645. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  77646. var hasBuffers = false;
  77647. var processBuffer = function (buf, buffer) {
  77648. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  77649. gltfRuntime.loadedBufferCount++;
  77650. if (bufferView) {
  77651. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  77652. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  77653. }
  77654. gltfRuntime.loadedBufferViews[buf] = bufferView;
  77655. }
  77656. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  77657. onLoad();
  77658. }
  77659. }, function () {
  77660. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  77661. });
  77662. };
  77663. for (var buf in gltfRuntime.buffers) {
  77664. hasBuffers = true;
  77665. var buffer = gltfRuntime.buffers[buf];
  77666. if (buffer) {
  77667. processBuffer.bind(this, buf, buffer)();
  77668. }
  77669. else {
  77670. BABYLON.Tools.Error("No buffer named: " + buf);
  77671. }
  77672. }
  77673. if (!hasBuffers) {
  77674. onLoad();
  77675. }
  77676. };
  77677. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  77678. var currentScene = gltfRuntime.currentScene;
  77679. if (currentScene) {
  77680. // Only one scene even if multiple scenes are defined
  77681. for (var i = 0; i < currentScene.nodes.length; i++) {
  77682. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77683. }
  77684. }
  77685. else {
  77686. // Load all scenes
  77687. for (var thing in gltfRuntime.scenes) {
  77688. currentScene = gltfRuntime.scenes[thing];
  77689. for (var i = 0; i < currentScene.nodes.length; i++) {
  77690. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77691. }
  77692. }
  77693. }
  77694. };
  77695. GLTFLoader.Extensions = {};
  77696. return GLTFLoader;
  77697. }());
  77698. GLTF1.GLTFLoader = GLTFLoader;
  77699. ;
  77700. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  77701. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77702. })(BABYLON || (BABYLON = {}));
  77703. //# sourceMappingURL=babylon.glTFLoader.js.map
  77704. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77705. var BABYLON;
  77706. (function (BABYLON) {
  77707. var GLTF1;
  77708. (function (GLTF1) {
  77709. /**
  77710. * Utils functions for GLTF
  77711. */
  77712. var GLTFUtils = /** @class */ (function () {
  77713. function GLTFUtils() {
  77714. }
  77715. /**
  77716. * Sets the given "parameter" matrix
  77717. * @param scene: the {BABYLON.Scene} object
  77718. * @param source: the source node where to pick the matrix
  77719. * @param parameter: the GLTF technique parameter
  77720. * @param uniformName: the name of the shader's uniform
  77721. * @param shaderMaterial: the shader material
  77722. */
  77723. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  77724. var mat = null;
  77725. if (parameter.semantic === "MODEL") {
  77726. mat = source.getWorldMatrix();
  77727. }
  77728. else if (parameter.semantic === "PROJECTION") {
  77729. mat = scene.getProjectionMatrix();
  77730. }
  77731. else if (parameter.semantic === "VIEW") {
  77732. mat = scene.getViewMatrix();
  77733. }
  77734. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  77735. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  77736. }
  77737. else if (parameter.semantic === "MODELVIEW") {
  77738. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  77739. }
  77740. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  77741. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  77742. }
  77743. else if (parameter.semantic === "MODELINVERSE") {
  77744. mat = source.getWorldMatrix().invert();
  77745. }
  77746. else if (parameter.semantic === "VIEWINVERSE") {
  77747. mat = scene.getViewMatrix().invert();
  77748. }
  77749. else if (parameter.semantic === "PROJECTIONINVERSE") {
  77750. mat = scene.getProjectionMatrix().invert();
  77751. }
  77752. else if (parameter.semantic === "MODELVIEWINVERSE") {
  77753. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  77754. }
  77755. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  77756. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  77757. }
  77758. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  77759. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  77760. }
  77761. else {
  77762. debugger;
  77763. }
  77764. if (mat) {
  77765. switch (parameter.type) {
  77766. case GLTF1.EParameterType.FLOAT_MAT2:
  77767. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  77768. break;
  77769. case GLTF1.EParameterType.FLOAT_MAT3:
  77770. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  77771. break;
  77772. case GLTF1.EParameterType.FLOAT_MAT4:
  77773. shaderMaterial.setMatrix(uniformName, mat);
  77774. break;
  77775. default: break;
  77776. }
  77777. }
  77778. };
  77779. /**
  77780. * Sets the given "parameter" matrix
  77781. * @param shaderMaterial: the shader material
  77782. * @param uniform: the name of the shader's uniform
  77783. * @param value: the value of the uniform
  77784. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  77785. */
  77786. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  77787. switch (type) {
  77788. case GLTF1.EParameterType.FLOAT:
  77789. shaderMaterial.setFloat(uniform, value);
  77790. return true;
  77791. case GLTF1.EParameterType.FLOAT_VEC2:
  77792. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  77793. return true;
  77794. case GLTF1.EParameterType.FLOAT_VEC3:
  77795. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  77796. return true;
  77797. case GLTF1.EParameterType.FLOAT_VEC4:
  77798. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  77799. return true;
  77800. default: return false;
  77801. }
  77802. };
  77803. /**
  77804. * If the uri is a base64 string
  77805. * @param uri: the uri to test
  77806. */
  77807. GLTFUtils.IsBase64 = function (uri) {
  77808. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  77809. };
  77810. /**
  77811. * Decode the base64 uri
  77812. * @param uri: the uri to decode
  77813. */
  77814. GLTFUtils.DecodeBase64 = function (uri) {
  77815. var decodedString = atob(uri.split(",")[1]);
  77816. var bufferLength = decodedString.length;
  77817. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  77818. for (var i = 0; i < bufferLength; i++) {
  77819. bufferView[i] = decodedString.charCodeAt(i);
  77820. }
  77821. return bufferView.buffer;
  77822. };
  77823. /**
  77824. * Returns the wrap mode of the texture
  77825. * @param mode: the mode value
  77826. */
  77827. GLTFUtils.GetWrapMode = function (mode) {
  77828. switch (mode) {
  77829. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  77830. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  77831. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77832. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77833. }
  77834. };
  77835. /**
  77836. * Returns the byte stride giving an accessor
  77837. * @param accessor: the GLTF accessor objet
  77838. */
  77839. GLTFUtils.GetByteStrideFromType = function (accessor) {
  77840. // Needs this function since "byteStride" isn't requiered in glTF format
  77841. var type = accessor.type;
  77842. switch (type) {
  77843. case "VEC2": return 2;
  77844. case "VEC3": return 3;
  77845. case "VEC4": return 4;
  77846. case "MAT2": return 4;
  77847. case "MAT3": return 9;
  77848. case "MAT4": return 16;
  77849. default: return 1;
  77850. }
  77851. };
  77852. /**
  77853. * Returns the texture filter mode giving a mode value
  77854. * @param mode: the filter mode value
  77855. */
  77856. GLTFUtils.GetTextureFilterMode = function (mode) {
  77857. switch (mode) {
  77858. case GLTF1.ETextureFilterType.LINEAR:
  77859. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  77860. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  77861. case GLTF1.ETextureFilterType.NEAREST:
  77862. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  77863. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  77864. }
  77865. };
  77866. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  77867. var byteOffset = bufferView.byteOffset + byteOffset;
  77868. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  77869. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  77870. throw new Error("Buffer access is out of range");
  77871. }
  77872. var buffer = loadedBufferView.buffer;
  77873. byteOffset += loadedBufferView.byteOffset;
  77874. switch (componentType) {
  77875. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  77876. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  77877. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  77878. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  77879. default: return new Float32Array(buffer, byteOffset, byteLength);
  77880. }
  77881. };
  77882. /**
  77883. * Returns a buffer from its accessor
  77884. * @param gltfRuntime: the GLTF runtime
  77885. * @param accessor: the GLTF accessor
  77886. */
  77887. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  77888. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  77889. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  77890. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  77891. };
  77892. /**
  77893. * Decodes a buffer view into a string
  77894. * @param view: the buffer view
  77895. */
  77896. GLTFUtils.DecodeBufferToText = function (view) {
  77897. var result = "";
  77898. var length = view.byteLength;
  77899. for (var i = 0; i < length; ++i) {
  77900. result += String.fromCharCode(view[i]);
  77901. }
  77902. return result;
  77903. };
  77904. /**
  77905. * Returns the default material of gltf. Related to
  77906. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  77907. * @param scene: the Babylon.js scene
  77908. */
  77909. GLTFUtils.GetDefaultMaterial = function (scene) {
  77910. if (!GLTFUtils._DefaultMaterial) {
  77911. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  77912. "precision highp float;",
  77913. "",
  77914. "uniform mat4 worldView;",
  77915. "uniform mat4 projection;",
  77916. "",
  77917. "attribute vec3 position;",
  77918. "",
  77919. "void main(void)",
  77920. "{",
  77921. " gl_Position = projection * worldView * vec4(position, 1.0);",
  77922. "}"
  77923. ].join("\n");
  77924. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  77925. "precision highp float;",
  77926. "",
  77927. "uniform vec4 u_emission;",
  77928. "",
  77929. "void main(void)",
  77930. "{",
  77931. " gl_FragColor = u_emission;",
  77932. "}"
  77933. ].join("\n");
  77934. var shaderPath = {
  77935. vertex: "GLTFDefaultMaterial",
  77936. fragment: "GLTFDefaultMaterial"
  77937. };
  77938. var options = {
  77939. attributes: ["position"],
  77940. uniforms: ["worldView", "projection", "u_emission"],
  77941. samplers: new Array(),
  77942. needAlphaBlending: false
  77943. };
  77944. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  77945. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  77946. }
  77947. return GLTFUtils._DefaultMaterial;
  77948. };
  77949. // The GLTF default material
  77950. GLTFUtils._DefaultMaterial = null;
  77951. return GLTFUtils;
  77952. }());
  77953. GLTF1.GLTFUtils = GLTFUtils;
  77954. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77955. })(BABYLON || (BABYLON = {}));
  77956. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  77957. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77958. var BABYLON;
  77959. (function (BABYLON) {
  77960. var GLTF1;
  77961. (function (GLTF1) {
  77962. var GLTFLoaderExtension = /** @class */ (function () {
  77963. function GLTFLoaderExtension(name) {
  77964. this._name = name;
  77965. }
  77966. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  77967. get: function () {
  77968. return this._name;
  77969. },
  77970. enumerable: true,
  77971. configurable: true
  77972. });
  77973. /**
  77974. * Defines an override for loading the runtime
  77975. * Return true to stop further extensions from loading the runtime
  77976. */
  77977. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77978. return false;
  77979. };
  77980. /**
  77981. * Defines an onverride for creating gltf runtime
  77982. * Return true to stop further extensions from creating the runtime
  77983. */
  77984. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77985. return false;
  77986. };
  77987. /**
  77988. * Defines an override for loading buffers
  77989. * Return true to stop further extensions from loading this buffer
  77990. */
  77991. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77992. return false;
  77993. };
  77994. /**
  77995. * Defines an override for loading texture buffers
  77996. * Return true to stop further extensions from loading this texture data
  77997. */
  77998. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77999. return false;
  78000. };
  78001. /**
  78002. * Defines an override for creating textures
  78003. * Return true to stop further extensions from loading this texture
  78004. */
  78005. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  78006. return false;
  78007. };
  78008. /**
  78009. * Defines an override for loading shader strings
  78010. * Return true to stop further extensions from loading this shader data
  78011. */
  78012. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78013. return false;
  78014. };
  78015. /**
  78016. * Defines an override for loading materials
  78017. * Return true to stop further extensions from loading this material
  78018. */
  78019. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78020. return false;
  78021. };
  78022. // ---------
  78023. // Utilities
  78024. // ---------
  78025. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78026. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78027. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  78028. }, function () {
  78029. setTimeout(function () {
  78030. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  78031. });
  78032. });
  78033. };
  78034. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78035. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78036. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  78037. }, function () {
  78038. setTimeout(function () {
  78039. onSuccess();
  78040. });
  78041. });
  78042. };
  78043. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  78044. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78045. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  78046. }, function () {
  78047. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  78048. });
  78049. };
  78050. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  78051. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  78052. };
  78053. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78054. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78055. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  78056. }, function () {
  78057. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  78058. });
  78059. };
  78060. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78061. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78062. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  78063. }, function () {
  78064. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  78065. });
  78066. };
  78067. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78068. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78069. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  78070. }, function () {
  78071. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  78072. });
  78073. };
  78074. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  78075. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78076. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  78077. }, function () {
  78078. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  78079. });
  78080. };
  78081. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  78082. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  78083. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  78084. if (func(loaderExtension)) {
  78085. return;
  78086. }
  78087. }
  78088. defaultFunc();
  78089. };
  78090. return GLTFLoaderExtension;
  78091. }());
  78092. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  78093. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78094. })(BABYLON || (BABYLON = {}));
  78095. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  78096. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78097. var BABYLON;
  78098. (function (BABYLON) {
  78099. var GLTF1;
  78100. (function (GLTF1) {
  78101. var BinaryExtensionBufferName = "binary_glTF";
  78102. ;
  78103. ;
  78104. var GLTFBinaryExtension = /** @class */ (function (_super) {
  78105. __extends(GLTFBinaryExtension, _super);
  78106. function GLTFBinaryExtension() {
  78107. return _super.call(this, "KHR_binary_glTF") || this;
  78108. }
  78109. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78110. var extensionsUsed = data.json.extensionsUsed;
  78111. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  78112. return false;
  78113. }
  78114. this._bin = data.bin;
  78115. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  78116. return true;
  78117. };
  78118. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78119. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  78120. return false;
  78121. }
  78122. if (id !== BinaryExtensionBufferName) {
  78123. return false;
  78124. }
  78125. onSuccess(this._bin);
  78126. return true;
  78127. };
  78128. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78129. var texture = gltfRuntime.textures[id];
  78130. var source = gltfRuntime.images[texture.source];
  78131. if (!source.extensions || !(this.name in source.extensions)) {
  78132. return false;
  78133. }
  78134. var sourceExt = source.extensions[this.name];
  78135. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  78136. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  78137. onSuccess(buffer);
  78138. return true;
  78139. };
  78140. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78141. var shader = gltfRuntime.shaders[id];
  78142. if (!shader.extensions || !(this.name in shader.extensions)) {
  78143. return false;
  78144. }
  78145. var binaryExtensionShader = shader.extensions[this.name];
  78146. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  78147. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  78148. setTimeout(function () {
  78149. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  78150. onSuccess(shaderString);
  78151. });
  78152. return true;
  78153. };
  78154. return GLTFBinaryExtension;
  78155. }(GLTF1.GLTFLoaderExtension));
  78156. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  78157. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  78158. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78159. })(BABYLON || (BABYLON = {}));
  78160. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  78161. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78162. var BABYLON;
  78163. (function (BABYLON) {
  78164. var GLTF1;
  78165. (function (GLTF1) {
  78166. ;
  78167. ;
  78168. ;
  78169. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  78170. __extends(GLTFMaterialsCommonExtension, _super);
  78171. function GLTFMaterialsCommonExtension() {
  78172. return _super.call(this, "KHR_materials_common") || this;
  78173. }
  78174. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78175. if (!gltfRuntime.extensions)
  78176. return false;
  78177. var extension = gltfRuntime.extensions[this.name];
  78178. if (!extension)
  78179. return false;
  78180. // Create lights
  78181. var lights = extension.lights;
  78182. if (lights) {
  78183. for (var thing in lights) {
  78184. var light = lights[thing];
  78185. switch (light.type) {
  78186. case "ambient":
  78187. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  78188. var ambient = light.ambient;
  78189. if (ambient) {
  78190. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  78191. }
  78192. break;
  78193. case "point":
  78194. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  78195. var point = light.point;
  78196. if (point) {
  78197. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  78198. }
  78199. break;
  78200. case "directional":
  78201. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  78202. var directional = light.directional;
  78203. if (directional) {
  78204. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  78205. }
  78206. break;
  78207. case "spot":
  78208. var spot = light.spot;
  78209. if (spot) {
  78210. 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);
  78211. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  78212. }
  78213. break;
  78214. default:
  78215. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  78216. break;
  78217. }
  78218. }
  78219. }
  78220. return false;
  78221. };
  78222. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78223. var material = gltfRuntime.materials[id];
  78224. if (!material || !material.extensions)
  78225. return false;
  78226. var extension = material.extensions[this.name];
  78227. if (!extension)
  78228. return false;
  78229. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  78230. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78231. if (extension.technique === "CONSTANT") {
  78232. standardMaterial.disableLighting = true;
  78233. }
  78234. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  78235. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  78236. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  78237. // Ambient
  78238. if (typeof extension.values.ambient === "string") {
  78239. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  78240. }
  78241. else {
  78242. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  78243. }
  78244. // Diffuse
  78245. if (typeof extension.values.diffuse === "string") {
  78246. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  78247. }
  78248. else {
  78249. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  78250. }
  78251. // Emission
  78252. if (typeof extension.values.emission === "string") {
  78253. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  78254. }
  78255. else {
  78256. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  78257. }
  78258. // Specular
  78259. if (typeof extension.values.specular === "string") {
  78260. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  78261. }
  78262. else {
  78263. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  78264. }
  78265. return true;
  78266. };
  78267. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  78268. // Create buffer from texture url
  78269. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  78270. // Create texture from buffer
  78271. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  78272. }, onError);
  78273. };
  78274. return GLTFMaterialsCommonExtension;
  78275. }(GLTF1.GLTFLoaderExtension));
  78276. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  78277. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  78278. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78279. })(BABYLON || (BABYLON = {}));
  78280. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  78281. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78282. var BABYLON;
  78283. (function (BABYLON) {
  78284. var GLTF2;
  78285. (function (GLTF2) {
  78286. /**
  78287. * Enums
  78288. */
  78289. var EComponentType;
  78290. (function (EComponentType) {
  78291. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  78292. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  78293. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  78294. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  78295. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  78296. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  78297. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  78298. var EMeshPrimitiveMode;
  78299. (function (EMeshPrimitiveMode) {
  78300. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  78301. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  78302. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  78303. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  78304. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  78305. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  78306. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  78307. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  78308. var ETextureMagFilter;
  78309. (function (ETextureMagFilter) {
  78310. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  78311. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  78312. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  78313. var ETextureMinFilter;
  78314. (function (ETextureMinFilter) {
  78315. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  78316. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  78317. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  78318. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  78319. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  78320. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  78321. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  78322. var ETextureWrapMode;
  78323. (function (ETextureWrapMode) {
  78324. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  78325. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  78326. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  78327. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  78328. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  78329. })(BABYLON || (BABYLON = {}));
  78330. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  78331. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78332. var BABYLON;
  78333. (function (BABYLON) {
  78334. var GLTF2;
  78335. (function (GLTF2) {
  78336. var GLTFLoaderTracker = /** @class */ (function () {
  78337. function GLTFLoaderTracker(onComplete) {
  78338. this._pendingCount = 0;
  78339. this._callback = onComplete;
  78340. }
  78341. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  78342. this._pendingCount++;
  78343. };
  78344. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  78345. if (--this._pendingCount === 0) {
  78346. this._callback();
  78347. }
  78348. };
  78349. return GLTFLoaderTracker;
  78350. }());
  78351. var GLTFLoader = /** @class */ (function () {
  78352. function GLTFLoader(parent) {
  78353. this._disposed = false;
  78354. this._renderReady = false;
  78355. this._requests = new Array();
  78356. this._renderReadyObservable = new BABYLON.Observable();
  78357. // Count of pending work that needs to complete before the asset is rendered.
  78358. this._renderPendingCount = 0;
  78359. // Count of pending work that needs to complete before the loader is disposed.
  78360. this._loaderPendingCount = 0;
  78361. this._loaderTrackers = new Array();
  78362. this._parent = parent;
  78363. }
  78364. GLTFLoader.RegisterExtension = function (extension) {
  78365. if (GLTFLoader.Extensions[extension.name]) {
  78366. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  78367. return;
  78368. }
  78369. GLTFLoader.Extensions[extension.name] = extension;
  78370. // Keep the order of registration so that extensions registered first are called first.
  78371. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  78372. };
  78373. GLTFLoader.prototype.dispose = function () {
  78374. if (this._disposed) {
  78375. return;
  78376. }
  78377. this._disposed = true;
  78378. // Abort requests that are not complete
  78379. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  78380. var request = _a[_i];
  78381. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  78382. request.abort();
  78383. }
  78384. }
  78385. // Revoke object urls created during load
  78386. if (this._gltf.textures) {
  78387. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  78388. var texture = _c[_b];
  78389. if (texture.url) {
  78390. URL.revokeObjectURL(texture.url);
  78391. }
  78392. }
  78393. }
  78394. };
  78395. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78396. var _this = this;
  78397. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  78398. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  78399. }, onProgress, onError);
  78400. };
  78401. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  78402. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  78403. };
  78404. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78405. var _this = this;
  78406. this._tryCatchOnError(function () {
  78407. _this._loadData(data);
  78408. _this._babylonScene = scene;
  78409. _this._rootUrl = rootUrl;
  78410. _this._successCallback = onSuccess;
  78411. _this._progressCallback = onProgress;
  78412. _this._errorCallback = onError;
  78413. _this._addPendingData(_this);
  78414. _this._loadDefaultScene(nodeNames);
  78415. _this._loadAnimations();
  78416. _this._removePendingData(_this);
  78417. });
  78418. };
  78419. GLTFLoader.prototype._onProgress = function (event) {
  78420. if (this._progressCallback) {
  78421. this._progressCallback(event);
  78422. }
  78423. };
  78424. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  78425. if (this._renderReady) {
  78426. func();
  78427. }
  78428. else {
  78429. this._renderReadyObservable.add(func);
  78430. }
  78431. };
  78432. GLTFLoader.prototype._onRenderReady = function () {
  78433. this._rootNode.babylonMesh.setEnabled(true);
  78434. this._startAnimations();
  78435. this._successCallback();
  78436. this._renderReadyObservable.notifyObservers(this);
  78437. };
  78438. GLTFLoader.prototype._onComplete = function () {
  78439. if (this._parent.onComplete) {
  78440. this._parent.onComplete();
  78441. }
  78442. this.dispose();
  78443. };
  78444. GLTFLoader.prototype._loadData = function (data) {
  78445. this._gltf = data.json;
  78446. // Assign the index of each object for convinience.
  78447. GLTFLoader._AssignIndices(this._gltf.accessors);
  78448. GLTFLoader._AssignIndices(this._gltf.animations);
  78449. GLTFLoader._AssignIndices(this._gltf.buffers);
  78450. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  78451. GLTFLoader._AssignIndices(this._gltf.images);
  78452. GLTFLoader._AssignIndices(this._gltf.materials);
  78453. GLTFLoader._AssignIndices(this._gltf.meshes);
  78454. GLTFLoader._AssignIndices(this._gltf.nodes);
  78455. GLTFLoader._AssignIndices(this._gltf.scenes);
  78456. GLTFLoader._AssignIndices(this._gltf.skins);
  78457. GLTFLoader._AssignIndices(this._gltf.textures);
  78458. if (data.bin) {
  78459. var buffers = this._gltf.buffers;
  78460. if (buffers && buffers[0] && !buffers[0].uri) {
  78461. var binaryBuffer = buffers[0];
  78462. if (binaryBuffer.byteLength != data.bin.byteLength) {
  78463. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  78464. }
  78465. binaryBuffer.loadedData = data.bin;
  78466. }
  78467. else {
  78468. BABYLON.Tools.Warn("Unexpected BIN chunk");
  78469. }
  78470. }
  78471. };
  78472. GLTFLoader.prototype._getMeshes = function () {
  78473. var meshes = new Array();
  78474. // Root mesh is always first.
  78475. meshes.push(this._rootNode.babylonMesh);
  78476. var nodes = this._gltf.nodes;
  78477. if (nodes) {
  78478. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  78479. var node = nodes_1[_i];
  78480. if (node.babylonMesh) {
  78481. meshes.push(node.babylonMesh);
  78482. }
  78483. }
  78484. }
  78485. return meshes;
  78486. };
  78487. GLTFLoader.prototype._getSkeletons = function () {
  78488. var skeletons = new Array();
  78489. var skins = this._gltf.skins;
  78490. if (skins) {
  78491. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  78492. var skin = skins_1[_i];
  78493. if (skin.babylonSkeleton) {
  78494. skeletons.push(skin.babylonSkeleton);
  78495. }
  78496. }
  78497. }
  78498. return skeletons;
  78499. };
  78500. GLTFLoader.prototype._getAnimationTargets = function () {
  78501. var targets = new Array();
  78502. var animations = this._gltf.animations;
  78503. if (animations) {
  78504. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  78505. var animation = animations_1[_i];
  78506. targets.push.apply(targets, animation.targets);
  78507. }
  78508. }
  78509. return targets;
  78510. };
  78511. GLTFLoader.prototype._startAnimations = function () {
  78512. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  78513. var target = _a[_i];
  78514. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  78515. }
  78516. };
  78517. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  78518. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  78519. if (!scene) {
  78520. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  78521. }
  78522. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  78523. };
  78524. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  78525. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  78526. switch (this._parent.coordinateSystemMode) {
  78527. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  78528. if (!this._babylonScene.useRightHandedSystem) {
  78529. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  78530. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  78531. }
  78532. break;
  78533. }
  78534. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
  78535. // do nothing
  78536. break;
  78537. }
  78538. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  78539. this._babylonScene.useRightHandedSystem = true;
  78540. break;
  78541. }
  78542. default: {
  78543. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  78544. return;
  78545. }
  78546. }
  78547. var nodeIndices = scene.nodes;
  78548. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  78549. node.parent = parentNode;
  78550. return true;
  78551. }, this._rootNode);
  78552. if (nodeNames) {
  78553. if (!(nodeNames instanceof Array)) {
  78554. nodeNames = [nodeNames];
  78555. }
  78556. var filteredNodeIndices_1 = new Array();
  78557. this._traverseNodes(context, nodeIndices, function (node) {
  78558. if (nodeNames.indexOf(node.name) !== -1) {
  78559. filteredNodeIndices_1.push(node.index);
  78560. return false;
  78561. }
  78562. return true;
  78563. }, this._rootNode);
  78564. nodeIndices = filteredNodeIndices_1;
  78565. }
  78566. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  78567. var index = nodeIndices_1[_i];
  78568. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  78569. if (!node) {
  78570. throw new Error(context + ": Failed to find node " + index);
  78571. }
  78572. this._loadNode("#/nodes/" + index, node);
  78573. }
  78574. // Disable the root mesh until the asset is ready to render.
  78575. this._rootNode.babylonMesh.setEnabled(false);
  78576. };
  78577. GLTFLoader.prototype._loadNode = function (context, node) {
  78578. node.babylonBones = {};
  78579. node.babylonAnimationTargets = [];
  78580. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  78581. return;
  78582. }
  78583. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  78584. this._loadTransform(node);
  78585. if (node.mesh != null) {
  78586. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  78587. if (!mesh) {
  78588. throw new Error(context + ": Failed to find mesh " + node.mesh);
  78589. }
  78590. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  78591. }
  78592. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  78593. node.babylonAnimationTargets.push(node.babylonMesh);
  78594. if (node.skin != null) {
  78595. var skin = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  78596. if (!skin) {
  78597. throw new Error(context + ": Failed to find skin " + node.skin);
  78598. }
  78599. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  78600. }
  78601. if (node.camera != null) {
  78602. // TODO: handle cameras
  78603. }
  78604. if (node.children) {
  78605. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  78606. var index = _a[_i];
  78607. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  78608. if (!childNode) {
  78609. throw new Error(context + ": Failed to find child node " + index);
  78610. }
  78611. this._loadNode("#/nodes/" + index, childNode);
  78612. }
  78613. }
  78614. };
  78615. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  78616. var _this = this;
  78617. var primitives = mesh.primitives;
  78618. if (!primitives || primitives.length === 0) {
  78619. throw new Error(context + ": Primitives are missing");
  78620. }
  78621. this._createMorphTargets(context, node, mesh);
  78622. this._loadAllVertexDataAsync(context, mesh, function () {
  78623. _this._loadMorphTargets(context, node, mesh);
  78624. var vertexData = new BABYLON.VertexData();
  78625. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  78626. var primitive = primitives_1[_i];
  78627. vertexData.merge(primitive.vertexData);
  78628. }
  78629. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  78630. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  78631. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  78632. node.babylonMesh.subMeshes = [];
  78633. var verticesStart = 0;
  78634. var indicesStart = 0;
  78635. for (var index = 0; index < primitives.length; index++) {
  78636. var vertexData_1 = primitives[index].vertexData;
  78637. var verticesCount = vertexData_1.positions.length;
  78638. var indicesCount = vertexData_1.indices.length;
  78639. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  78640. verticesStart += verticesCount;
  78641. indicesStart += indicesCount;
  78642. }
  78643. ;
  78644. });
  78645. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  78646. node.babylonMesh.material = multiMaterial;
  78647. var subMaterials = multiMaterial.subMaterials;
  78648. var _loop_1 = function (index) {
  78649. var primitive = primitives[index];
  78650. if (primitive.material == null) {
  78651. subMaterials[index] = this_1._getDefaultMaterial();
  78652. }
  78653. else {
  78654. var material_1 = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  78655. if (!material_1) {
  78656. throw new Error(context + ": Failed to find material " + primitive.material);
  78657. }
  78658. this_1._loadMaterial("#/materials/" + material_1.index, material_1, function (babylonMaterial, isNew) {
  78659. if (isNew && _this._parent.onMaterialLoaded) {
  78660. _this._parent.onMaterialLoaded(babylonMaterial);
  78661. }
  78662. if (_this._parent.onBeforeMaterialReadyAsync) {
  78663. _this._addLoaderPendingData(material_1);
  78664. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  78665. _this._tryCatchOnError(function () {
  78666. subMaterials[index] = babylonMaterial;
  78667. _this._removeLoaderPendingData(material_1);
  78668. });
  78669. });
  78670. }
  78671. else {
  78672. subMaterials[index] = babylonMaterial;
  78673. }
  78674. });
  78675. }
  78676. };
  78677. var this_1 = this;
  78678. for (var index = 0; index < primitives.length; index++) {
  78679. _loop_1(index);
  78680. }
  78681. ;
  78682. };
  78683. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  78684. var primitives = mesh.primitives;
  78685. var numRemainingPrimitives = primitives.length;
  78686. var _loop_2 = function (index) {
  78687. var primitive = primitives[index];
  78688. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  78689. primitive.vertexData = vertexData;
  78690. if (--numRemainingPrimitives === 0) {
  78691. onSuccess();
  78692. }
  78693. });
  78694. };
  78695. var this_2 = this;
  78696. for (var index = 0; index < primitives.length; index++) {
  78697. _loop_2(index);
  78698. }
  78699. };
  78700. /**
  78701. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  78702. * @param {ArrayBufferView} data
  78703. * @param {IGLTFAccessor} accessor
  78704. */
  78705. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  78706. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  78707. return data;
  78708. }
  78709. var buffer = data;
  78710. var factor = 1;
  78711. switch (accessor.componentType) {
  78712. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  78713. factor = 1 / 255;
  78714. break;
  78715. }
  78716. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  78717. factor = 1 / 65535;
  78718. break;
  78719. }
  78720. default: {
  78721. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78722. }
  78723. }
  78724. var result = new Float32Array(accessor.count * 2);
  78725. for (var i = 0; i < result.length; ++i) {
  78726. result[i] = buffer[i] * factor;
  78727. }
  78728. return result;
  78729. };
  78730. /**
  78731. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  78732. * @param {ArrayBufferView} data
  78733. * @param {IGLTFAccessor} accessor
  78734. */
  78735. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  78736. var colorComponentCount = GLTFLoader._GetNumComponents(accessor.type);
  78737. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  78738. return data;
  78739. }
  78740. var buffer = data;
  78741. var factor = 1;
  78742. switch (accessor.componentType) {
  78743. case GLTF2.EComponentType.FLOAT: {
  78744. factor = 1;
  78745. break;
  78746. }
  78747. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  78748. factor = 1 / 255;
  78749. break;
  78750. }
  78751. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  78752. factor = 1 / 65535;
  78753. break;
  78754. }
  78755. default: {
  78756. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78757. }
  78758. }
  78759. var result = new Float32Array(accessor.count * 4);
  78760. if (colorComponentCount === 4) {
  78761. for (var i = 0; i < result.length; ++i) {
  78762. result[i] = buffer[i] * factor;
  78763. }
  78764. }
  78765. else {
  78766. var offset = 0;
  78767. for (var i = 0; i < result.length; ++i) {
  78768. if ((i + 1) % 4 === 0) {
  78769. result[i] = 1;
  78770. }
  78771. else {
  78772. result[i] = buffer[offset++] * factor;
  78773. }
  78774. }
  78775. }
  78776. return result;
  78777. };
  78778. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  78779. var _this = this;
  78780. var attributes = primitive.attributes;
  78781. if (!attributes) {
  78782. throw new Error(context + ": Attributes are missing");
  78783. }
  78784. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  78785. // TODO: handle other primitive modes
  78786. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  78787. }
  78788. var vertexData = new BABYLON.VertexData();
  78789. var numRemainingAttributes = Object.keys(attributes).length;
  78790. var _loop_3 = function (attribute) {
  78791. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  78792. if (!accessor) {
  78793. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  78794. }
  78795. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78796. switch (attribute) {
  78797. case "POSITION": {
  78798. vertexData.positions = data;
  78799. break;
  78800. }
  78801. case "NORMAL": {
  78802. vertexData.normals = data;
  78803. break;
  78804. }
  78805. case "TANGENT": {
  78806. vertexData.tangents = data;
  78807. break;
  78808. }
  78809. case "TEXCOORD_0": {
  78810. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  78811. break;
  78812. }
  78813. case "TEXCOORD_1": {
  78814. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  78815. break;
  78816. }
  78817. case "JOINTS_0": {
  78818. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  78819. break;
  78820. }
  78821. case "WEIGHTS_0": {
  78822. //TODO: need to add support for normalized weights.
  78823. vertexData.matricesWeights = data;
  78824. break;
  78825. }
  78826. case "COLOR_0": {
  78827. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  78828. break;
  78829. }
  78830. default: {
  78831. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  78832. break;
  78833. }
  78834. }
  78835. if (--numRemainingAttributes === 0) {
  78836. if (primitive.indices == null) {
  78837. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  78838. for (var i = 0; i < vertexData.indices.length; i++) {
  78839. vertexData.indices[i] = i;
  78840. }
  78841. onSuccess(vertexData);
  78842. }
  78843. else {
  78844. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  78845. if (!indicesAccessor) {
  78846. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  78847. }
  78848. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  78849. vertexData.indices = data;
  78850. onSuccess(vertexData);
  78851. });
  78852. }
  78853. }
  78854. });
  78855. };
  78856. var this_3 = this;
  78857. for (var attribute in attributes) {
  78858. _loop_3(attribute);
  78859. }
  78860. };
  78861. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  78862. var primitives = mesh.primitives;
  78863. var targets = primitives[0].targets;
  78864. if (!targets) {
  78865. return;
  78866. }
  78867. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  78868. var primitive = primitives_2[_i];
  78869. if (!primitive.targets || primitive.targets.length != targets.length) {
  78870. throw new Error(context + ": All primitives are required to list the same number of targets");
  78871. }
  78872. }
  78873. var morphTargetManager = new BABYLON.MorphTargetManager();
  78874. node.babylonMesh.morphTargetManager = morphTargetManager;
  78875. for (var index = 0; index < targets.length; index++) {
  78876. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  78877. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  78878. }
  78879. };
  78880. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  78881. var morphTargetManager = node.babylonMesh.morphTargetManager;
  78882. if (!morphTargetManager) {
  78883. return;
  78884. }
  78885. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  78886. var numTargets = morphTargetManager.numTargets;
  78887. for (var index = 0; index < numTargets; index++) {
  78888. var vertexData = new BABYLON.VertexData();
  78889. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78890. var primitive = _a[_i];
  78891. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  78892. }
  78893. if (!vertexData.positions) {
  78894. throw new Error(context + ": Positions are missing");
  78895. }
  78896. var target = morphTargetManager.getTarget(index);
  78897. target.setPositions(vertexData.positions);
  78898. target.setNormals(vertexData.normals);
  78899. target.setTangents(vertexData.tangents);
  78900. }
  78901. });
  78902. };
  78903. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  78904. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  78905. var _loop_4 = function (primitive) {
  78906. var targets = primitive.targets;
  78907. primitive.targetsVertexData = new Array(targets.length);
  78908. var _loop_5 = function (index) {
  78909. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  78910. primitive.targetsVertexData[index] = vertexData;
  78911. if (--numRemainingTargets === 0) {
  78912. onSuccess();
  78913. }
  78914. });
  78915. };
  78916. for (var index = 0; index < targets.length; index++) {
  78917. _loop_5(index);
  78918. }
  78919. };
  78920. var this_4 = this;
  78921. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78922. var primitive = _a[_i];
  78923. _loop_4(primitive);
  78924. }
  78925. };
  78926. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  78927. var targetVertexData = new BABYLON.VertexData();
  78928. var numRemainingAttributes = Object.keys(attributes).length;
  78929. var _loop_6 = function (attribute) {
  78930. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  78931. if (!accessor) {
  78932. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  78933. }
  78934. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78935. // glTF stores morph target information as deltas while babylon.js expects the final data.
  78936. // As a result we have to add the original data to the delta to calculate the final data.
  78937. var values = data;
  78938. switch (attribute) {
  78939. case "POSITION": {
  78940. for (var i = 0; i < values.length; i++) {
  78941. values[i] += vertexData.positions[i];
  78942. }
  78943. targetVertexData.positions = values;
  78944. break;
  78945. }
  78946. case "NORMAL": {
  78947. for (var i = 0; i < values.length; i++) {
  78948. values[i] += vertexData.normals[i];
  78949. }
  78950. targetVertexData.normals = values;
  78951. break;
  78952. }
  78953. case "TANGENT": {
  78954. // Tangent data for morph targets is stored as xyz delta.
  78955. // The vertexData.tangent is stored as xyzw.
  78956. // So we need to skip every fourth vertexData.tangent.
  78957. for (var i = 0, j = 0; i < values.length; i++, j++) {
  78958. values[i] += vertexData.tangents[j];
  78959. if ((i + 1) % 3 == 0) {
  78960. j++;
  78961. }
  78962. }
  78963. targetVertexData.tangents = values;
  78964. break;
  78965. }
  78966. default: {
  78967. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  78968. break;
  78969. }
  78970. }
  78971. if (--numRemainingAttributes === 0) {
  78972. onSuccess(targetVertexData);
  78973. }
  78974. });
  78975. };
  78976. var this_5 = this;
  78977. for (var attribute in attributes) {
  78978. _loop_6(attribute);
  78979. }
  78980. };
  78981. GLTFLoader.prototype._loadTransform = function (node) {
  78982. var position = BABYLON.Vector3.Zero();
  78983. var rotation = BABYLON.Quaternion.Identity();
  78984. var scaling = BABYLON.Vector3.One();
  78985. if (node.matrix) {
  78986. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  78987. matrix.decompose(scaling, rotation, position);
  78988. }
  78989. else {
  78990. if (node.translation)
  78991. position = BABYLON.Vector3.FromArray(node.translation);
  78992. if (node.rotation)
  78993. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  78994. if (node.scale)
  78995. scaling = BABYLON.Vector3.FromArray(node.scale);
  78996. }
  78997. node.babylonMesh.position = position;
  78998. node.babylonMesh.rotationQuaternion = rotation;
  78999. node.babylonMesh.scaling = scaling;
  79000. };
  79001. GLTFLoader.prototype._loadSkin = function (context, skin) {
  79002. var _this = this;
  79003. var skeletonId = "skeleton" + skin.index;
  79004. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  79005. if (skin.inverseBindMatrices == null) {
  79006. this._loadBones(context, skin, null);
  79007. }
  79008. else {
  79009. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  79010. if (!accessor) {
  79011. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  79012. }
  79013. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  79014. _this._loadBones(context, skin, data);
  79015. });
  79016. }
  79017. return skin.babylonSkeleton;
  79018. };
  79019. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  79020. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  79021. node.babylonBones[skin.index] = babylonBone;
  79022. node.babylonAnimationTargets.push(babylonBone);
  79023. return babylonBone;
  79024. };
  79025. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  79026. var babylonBones = {};
  79027. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  79028. var index = _a[_i];
  79029. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  79030. if (!node) {
  79031. throw new Error(context + ": Failed to find joint " + index);
  79032. }
  79033. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  79034. }
  79035. };
  79036. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  79037. var babylonBone = babylonBones[node.index];
  79038. if (babylonBone) {
  79039. return babylonBone;
  79040. }
  79041. var boneIndex = skin.joints.indexOf(node.index);
  79042. var baseMatrix = BABYLON.Matrix.Identity();
  79043. if (inverseBindMatrixData && boneIndex !== -1) {
  79044. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  79045. baseMatrix.invertToRef(baseMatrix);
  79046. }
  79047. var babylonParentBone = null;
  79048. if (node.index !== skin.skeleton && node.parent && node.parent !== this._rootNode) {
  79049. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  79050. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  79051. }
  79052. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  79053. babylonBones[node.index] = babylonBone;
  79054. return babylonBone;
  79055. };
  79056. GLTFLoader.prototype._getNodeMatrix = function (node) {
  79057. return node.matrix ?
  79058. BABYLON.Matrix.FromArray(node.matrix) :
  79059. 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());
  79060. };
  79061. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  79062. if (parentNode === void 0) { parentNode = null; }
  79063. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  79064. var index = indices_1[_i];
  79065. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  79066. if (!node) {
  79067. throw new Error(context + ": Failed to find node " + index);
  79068. }
  79069. this._traverseNode(context, node, action, parentNode);
  79070. }
  79071. };
  79072. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  79073. if (parentNode === void 0) { parentNode = null; }
  79074. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  79075. return;
  79076. }
  79077. if (!action(node, parentNode)) {
  79078. return;
  79079. }
  79080. if (node.children) {
  79081. this._traverseNodes(context, node.children, action, node);
  79082. }
  79083. };
  79084. GLTFLoader.prototype._loadAnimations = function () {
  79085. var animations = this._gltf.animations;
  79086. if (!animations) {
  79087. return;
  79088. }
  79089. for (var index = 0; index < animations.length; index++) {
  79090. var animation = animations[index];
  79091. this._loadAnimation("#/animations/" + index, animation);
  79092. }
  79093. };
  79094. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  79095. animation.targets = [];
  79096. for (var index = 0; index < animation.channels.length; index++) {
  79097. var channel = GLTFLoader._GetProperty(animation.channels, index);
  79098. if (!channel) {
  79099. throw new Error(context + ": Failed to find channel " + index);
  79100. }
  79101. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  79102. if (!sampler) {
  79103. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  79104. }
  79105. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  79106. }
  79107. };
  79108. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  79109. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  79110. if (!targetNode) {
  79111. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  79112. }
  79113. var targetPath;
  79114. var animationType;
  79115. switch (channel.target.path) {
  79116. case "translation": {
  79117. targetPath = "position";
  79118. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  79119. break;
  79120. }
  79121. case "rotation": {
  79122. targetPath = "rotationQuaternion";
  79123. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  79124. break;
  79125. }
  79126. case "scale": {
  79127. targetPath = "scaling";
  79128. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  79129. break;
  79130. }
  79131. case "weights": {
  79132. targetPath = "influence";
  79133. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  79134. break;
  79135. }
  79136. default: {
  79137. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  79138. }
  79139. }
  79140. var inputData;
  79141. var outputData;
  79142. var checkSuccess = function () {
  79143. if (!inputData || !outputData) {
  79144. return;
  79145. }
  79146. var outputBufferOffset = 0;
  79147. var getNextOutputValue;
  79148. switch (targetPath) {
  79149. case "position": {
  79150. getNextOutputValue = function () {
  79151. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  79152. outputBufferOffset += 3;
  79153. return value;
  79154. };
  79155. break;
  79156. }
  79157. case "rotationQuaternion": {
  79158. getNextOutputValue = function () {
  79159. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  79160. outputBufferOffset += 4;
  79161. return value;
  79162. };
  79163. break;
  79164. }
  79165. case "scaling": {
  79166. getNextOutputValue = function () {
  79167. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  79168. outputBufferOffset += 3;
  79169. return value;
  79170. };
  79171. break;
  79172. }
  79173. case "influence": {
  79174. getNextOutputValue = function () {
  79175. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  79176. var value = new Array(numTargets);
  79177. for (var i = 0; i < numTargets; i++) {
  79178. value[i] = outputData[outputBufferOffset++];
  79179. }
  79180. return value;
  79181. };
  79182. break;
  79183. }
  79184. }
  79185. var getNextKey;
  79186. switch (sampler.interpolation) {
  79187. case "LINEAR": {
  79188. getNextKey = function (frameIndex) { return ({
  79189. frame: inputData[frameIndex],
  79190. value: getNextOutputValue()
  79191. }); };
  79192. break;
  79193. }
  79194. case "CUBICSPLINE": {
  79195. getNextKey = function (frameIndex) { return ({
  79196. frame: inputData[frameIndex],
  79197. inTangent: getNextOutputValue(),
  79198. value: getNextOutputValue(),
  79199. outTangent: getNextOutputValue()
  79200. }); };
  79201. break;
  79202. }
  79203. default: {
  79204. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  79205. }
  79206. }
  79207. ;
  79208. var keys = new Array(inputData.length);
  79209. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  79210. keys[frameIndex] = getNextKey(frameIndex);
  79211. }
  79212. if (targetPath === "influence") {
  79213. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  79214. var _loop_7 = function (targetIndex) {
  79215. var morphTarget = morphTargetManager.getTarget(targetIndex);
  79216. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  79217. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  79218. babylonAnimation.setKeys(keys.map(function (key) { return ({
  79219. frame: key.frame,
  79220. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  79221. value: key.value[targetIndex],
  79222. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  79223. }); }));
  79224. morphTarget.animations.push(babylonAnimation);
  79225. animation.targets.push(morphTarget);
  79226. };
  79227. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  79228. _loop_7(targetIndex);
  79229. }
  79230. }
  79231. else {
  79232. var animationName = animation.name || "anim" + animation.index;
  79233. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  79234. babylonAnimation.setKeys(keys);
  79235. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  79236. var target = _a[_i];
  79237. target.animations.push(babylonAnimation.clone());
  79238. animation.targets.push(target);
  79239. }
  79240. }
  79241. };
  79242. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  79243. if (!inputAccessor) {
  79244. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  79245. }
  79246. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  79247. inputData = data;
  79248. checkSuccess();
  79249. });
  79250. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  79251. if (!outputAccessor) {
  79252. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  79253. }
  79254. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  79255. outputData = data;
  79256. checkSuccess();
  79257. });
  79258. };
  79259. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  79260. var _this = this;
  79261. this._addPendingData(buffer);
  79262. if (buffer.loadedData) {
  79263. onSuccess(buffer.loadedData);
  79264. this._removePendingData(buffer);
  79265. }
  79266. else if (buffer.loadedObservable) {
  79267. buffer.loadedObservable.add(function (buffer) {
  79268. onSuccess(buffer.loadedData);
  79269. _this._removePendingData(buffer);
  79270. });
  79271. }
  79272. else {
  79273. if (!buffer.uri) {
  79274. throw new Error(context + ": Uri is missing");
  79275. }
  79276. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  79277. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  79278. buffer.loadedData = new Uint8Array(data);
  79279. onSuccess(buffer.loadedData);
  79280. this._removePendingData(buffer);
  79281. }
  79282. else {
  79283. buffer.loadedObservable = new BABYLON.Observable();
  79284. buffer.loadedObservable.add(function (buffer) {
  79285. onSuccess(buffer.loadedData);
  79286. _this._removePendingData(buffer);
  79287. });
  79288. this._loadUri(context, buffer.uri, function (data) {
  79289. buffer.loadedData = data;
  79290. buffer.loadedObservable.notifyObservers(buffer);
  79291. buffer.loadedObservable = undefined;
  79292. });
  79293. }
  79294. }
  79295. };
  79296. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  79297. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  79298. if (!buffer) {
  79299. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  79300. }
  79301. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  79302. var data;
  79303. try {
  79304. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  79305. }
  79306. catch (e) {
  79307. throw new Error(context + ": " + e.message);
  79308. }
  79309. onSuccess(data);
  79310. });
  79311. };
  79312. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  79313. var _this = this;
  79314. if (accessor.sparse) {
  79315. throw new Error(context + ": Sparse accessors are not currently supported");
  79316. }
  79317. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  79318. if (!bufferView) {
  79319. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  79320. }
  79321. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  79322. var numComponents = GLTFLoader._GetNumComponents(accessor.type);
  79323. if (numComponents === 0) {
  79324. throw new Error(context + ": Invalid type " + accessor.type);
  79325. }
  79326. var data;
  79327. var byteOffset = accessor.byteOffset || 0;
  79328. var byteStride = bufferView.byteStride;
  79329. try {
  79330. switch (accessor.componentType) {
  79331. case GLTF2.EComponentType.BYTE: {
  79332. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79333. break;
  79334. }
  79335. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  79336. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79337. break;
  79338. }
  79339. case GLTF2.EComponentType.SHORT: {
  79340. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79341. break;
  79342. }
  79343. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  79344. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79345. break;
  79346. }
  79347. case GLTF2.EComponentType.UNSIGNED_INT: {
  79348. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79349. break;
  79350. }
  79351. case GLTF2.EComponentType.FLOAT: {
  79352. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79353. break;
  79354. }
  79355. default: {
  79356. throw new Error(context + ": Invalid component type " + accessor.componentType);
  79357. }
  79358. }
  79359. }
  79360. catch (e) {
  79361. throw new Error(context + ": " + e);
  79362. }
  79363. onSuccess(data);
  79364. });
  79365. };
  79366. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  79367. byteOffset += data.byteOffset;
  79368. var targetLength = count * numComponents;
  79369. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  79370. return new typedArray(data.buffer, byteOffset, targetLength);
  79371. }
  79372. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  79373. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  79374. var targetBuffer = new typedArray(targetLength);
  79375. var sourceIndex = 0;
  79376. var targetIndex = 0;
  79377. while (targetIndex < targetLength) {
  79378. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  79379. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  79380. targetIndex++;
  79381. }
  79382. sourceIndex += elementStride;
  79383. }
  79384. return targetBuffer;
  79385. };
  79386. GLTFLoader.prototype._addPendingData = function (data) {
  79387. if (!this._renderReady) {
  79388. this._renderPendingCount++;
  79389. }
  79390. this._addLoaderPendingData(data);
  79391. };
  79392. GLTFLoader.prototype._removePendingData = function (data) {
  79393. if (!this._renderReady) {
  79394. if (--this._renderPendingCount === 0) {
  79395. this._renderReady = true;
  79396. this._onRenderReady();
  79397. }
  79398. }
  79399. this._removeLoaderPendingData(data);
  79400. };
  79401. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  79402. this._loaderPendingCount++;
  79403. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  79404. var tracker = _a[_i];
  79405. tracker._addPendingData(data);
  79406. }
  79407. };
  79408. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  79409. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  79410. var tracker = _a[_i];
  79411. tracker._removePendingData(data);
  79412. }
  79413. if (--this._loaderPendingCount === 0) {
  79414. this._onComplete();
  79415. }
  79416. };
  79417. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  79418. var _this = this;
  79419. var tracker = new GLTFLoaderTracker(function () {
  79420. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  79421. onComplete();
  79422. });
  79423. this._loaderTrackers.push(tracker);
  79424. this._addLoaderPendingData(tracker);
  79425. action();
  79426. this._removeLoaderPendingData(tracker);
  79427. };
  79428. GLTFLoader.prototype._getDefaultMaterial = function () {
  79429. if (!this._defaultMaterial) {
  79430. var id = "__gltf_default";
  79431. var material = this._babylonScene.getMaterialByName(id);
  79432. if (!material) {
  79433. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  79434. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79435. material.metallic = 1;
  79436. material.roughness = 1;
  79437. }
  79438. this._defaultMaterial = material;
  79439. }
  79440. return this._defaultMaterial;
  79441. };
  79442. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  79443. var babylonMaterial = material.babylonMaterial;
  79444. // Ensure metallic workflow
  79445. babylonMaterial.metallic = 1;
  79446. babylonMaterial.roughness = 1;
  79447. var properties = material.pbrMetallicRoughness;
  79448. if (!properties) {
  79449. return;
  79450. }
  79451. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  79452. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  79453. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  79454. if (properties.baseColorTexture) {
  79455. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  79456. if (!texture) {
  79457. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  79458. }
  79459. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  79460. }
  79461. if (properties.metallicRoughnessTexture) {
  79462. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  79463. if (!texture) {
  79464. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  79465. }
  79466. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  79467. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  79468. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  79469. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  79470. }
  79471. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  79472. };
  79473. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  79474. if (material.babylonMaterial) {
  79475. assign(material.babylonMaterial, false);
  79476. return;
  79477. }
  79478. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  79479. return;
  79480. }
  79481. this._createPbrMaterial(material);
  79482. this._loadMaterialBaseProperties(context, material);
  79483. this._loadMaterialMetallicRoughnessProperties(context, material);
  79484. assign(material.babylonMaterial, true);
  79485. };
  79486. GLTFLoader.prototype._createPbrMaterial = function (material) {
  79487. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  79488. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79489. material.babylonMaterial = babylonMaterial;
  79490. };
  79491. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  79492. var babylonMaterial = material.babylonMaterial;
  79493. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  79494. if (material.doubleSided) {
  79495. babylonMaterial.backFaceCulling = false;
  79496. babylonMaterial.twoSidedLighting = true;
  79497. }
  79498. if (material.normalTexture) {
  79499. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  79500. if (!texture) {
  79501. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  79502. }
  79503. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  79504. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  79505. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  79506. if (material.normalTexture.scale != null) {
  79507. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  79508. }
  79509. }
  79510. if (material.occlusionTexture) {
  79511. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  79512. if (!texture) {
  79513. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  79514. }
  79515. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  79516. babylonMaterial.useAmbientInGrayScale = true;
  79517. if (material.occlusionTexture.strength != null) {
  79518. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  79519. }
  79520. }
  79521. if (material.emissiveTexture) {
  79522. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  79523. if (!texture) {
  79524. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  79525. }
  79526. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  79527. }
  79528. };
  79529. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  79530. var babylonMaterial = material.babylonMaterial;
  79531. var alphaMode = material.alphaMode || "OPAQUE";
  79532. switch (alphaMode) {
  79533. case "OPAQUE": {
  79534. // default is opaque
  79535. break;
  79536. }
  79537. case "MASK": {
  79538. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  79539. if (colorFactor) {
  79540. if (colorFactor[3] == 0) {
  79541. babylonMaterial.alphaCutOff = 1;
  79542. }
  79543. else {
  79544. babylonMaterial.alphaCutOff /= colorFactor[3];
  79545. }
  79546. }
  79547. if (babylonMaterial.albedoTexture) {
  79548. babylonMaterial.albedoTexture.hasAlpha = true;
  79549. }
  79550. break;
  79551. }
  79552. case "BLEND": {
  79553. if (colorFactor) {
  79554. babylonMaterial.alpha = colorFactor[3];
  79555. }
  79556. if (babylonMaterial.albedoTexture) {
  79557. babylonMaterial.albedoTexture.hasAlpha = true;
  79558. babylonMaterial.useAlphaFromAlbedoTexture = true;
  79559. }
  79560. break;
  79561. }
  79562. default: {
  79563. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  79564. }
  79565. }
  79566. };
  79567. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  79568. var _this = this;
  79569. var sampler = (texture.sampler == null ? {} : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  79570. if (!sampler) {
  79571. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  79572. }
  79573. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  79574. var samplingMode = GLTFLoader._GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  79575. this._addPendingData(texture);
  79576. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  79577. _this._tryCatchOnError(function () {
  79578. _this._removePendingData(texture);
  79579. });
  79580. }, function (message) {
  79581. _this._tryCatchOnError(function () {
  79582. throw new Error(context + ": " + message);
  79583. });
  79584. });
  79585. if (texture.url) {
  79586. babylonTexture.updateURL(texture.url);
  79587. }
  79588. else if (texture.dataReadyObservable) {
  79589. texture.dataReadyObservable.add(function (texture) {
  79590. babylonTexture.updateURL(texture.url);
  79591. });
  79592. }
  79593. else {
  79594. texture.dataReadyObservable = new BABYLON.Observable();
  79595. texture.dataReadyObservable.add(function (texture) {
  79596. babylonTexture.updateURL(texture.url);
  79597. });
  79598. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  79599. if (!image_1) {
  79600. throw new Error(context + ": Failed to find source " + texture.source);
  79601. }
  79602. this._loadImage("#/images/" + image_1.index, image_1, function (data) {
  79603. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  79604. texture.dataReadyObservable.notifyObservers(texture);
  79605. texture.dataReadyObservable = undefined;
  79606. });
  79607. }
  79608. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  79609. babylonTexture.wrapU = GLTFLoader._GetTextureWrapMode(sampler.wrapS);
  79610. babylonTexture.wrapV = GLTFLoader._GetTextureWrapMode(sampler.wrapT);
  79611. babylonTexture.name = texture.name || "texture" + texture.index;
  79612. if (this._parent.onTextureLoaded) {
  79613. this._parent.onTextureLoaded(babylonTexture);
  79614. }
  79615. return babylonTexture;
  79616. };
  79617. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  79618. if (image.uri) {
  79619. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  79620. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  79621. }
  79622. else {
  79623. this._loadUri(context, image.uri, onSuccess);
  79624. }
  79625. }
  79626. else {
  79627. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  79628. if (!bufferView) {
  79629. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  79630. }
  79631. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  79632. }
  79633. };
  79634. GLTFLoader.prototype._loadUri = function (context, uri, onSuccess) {
  79635. var _this = this;
  79636. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  79637. throw new Error(context + ": Uri '" + uri + "' is invalid");
  79638. }
  79639. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  79640. _this._tryCatchOnError(function () {
  79641. onSuccess(new Uint8Array(data));
  79642. });
  79643. }, function (event) {
  79644. _this._tryCatchOnError(function () {
  79645. _this._onProgress(event);
  79646. });
  79647. }, this._babylonScene.database, true, function (request) {
  79648. _this._tryCatchOnError(function () {
  79649. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  79650. });
  79651. });
  79652. if (request) {
  79653. this._requests.push(request);
  79654. }
  79655. };
  79656. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  79657. if (this._disposed) {
  79658. return;
  79659. }
  79660. try {
  79661. handler();
  79662. }
  79663. catch (e) {
  79664. BABYLON.Tools.Error("glTF Loader: " + e.message);
  79665. if (this._errorCallback) {
  79666. this._errorCallback(e.message);
  79667. }
  79668. this.dispose();
  79669. }
  79670. };
  79671. GLTFLoader._AssignIndices = function (array) {
  79672. if (array) {
  79673. for (var index = 0; index < array.length; index++) {
  79674. array[index].index = index;
  79675. }
  79676. }
  79677. };
  79678. GLTFLoader._GetProperty = function (array, index) {
  79679. if (!array || index == undefined || !array[index]) {
  79680. return null;
  79681. }
  79682. return array[index];
  79683. };
  79684. GLTFLoader._GetTextureWrapMode = function (mode) {
  79685. // Set defaults if undefined
  79686. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  79687. switch (mode) {
  79688. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  79689. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  79690. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  79691. default:
  79692. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  79693. return BABYLON.Texture.WRAP_ADDRESSMODE;
  79694. }
  79695. };
  79696. GLTFLoader._GetTextureSamplingMode = function (magFilter, minFilter) {
  79697. // Set defaults if undefined
  79698. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  79699. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  79700. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  79701. switch (minFilter) {
  79702. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  79703. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  79704. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  79705. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  79706. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  79707. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79708. default:
  79709. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79710. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79711. }
  79712. }
  79713. else {
  79714. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  79715. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  79716. }
  79717. switch (minFilter) {
  79718. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  79719. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  79720. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79721. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  79722. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  79723. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  79724. default:
  79725. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79726. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79727. }
  79728. }
  79729. };
  79730. GLTFLoader._GetNumComponents = function (type) {
  79731. switch (type) {
  79732. case "SCALAR": return 1;
  79733. case "VEC2": return 2;
  79734. case "VEC3": return 3;
  79735. case "VEC4": return 4;
  79736. case "MAT2": return 4;
  79737. case "MAT3": return 9;
  79738. case "MAT4": return 16;
  79739. }
  79740. return 0;
  79741. };
  79742. GLTFLoader.Extensions = {};
  79743. return GLTFLoader;
  79744. }());
  79745. GLTF2.GLTFLoader = GLTFLoader;
  79746. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  79747. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79748. })(BABYLON || (BABYLON = {}));
  79749. //# sourceMappingURL=babylon.glTFLoader.js.map
  79750. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79751. var BABYLON;
  79752. (function (BABYLON) {
  79753. var GLTF2;
  79754. (function (GLTF2) {
  79755. /**
  79756. * Utils functions for GLTF
  79757. */
  79758. var GLTFUtils = /** @class */ (function () {
  79759. function GLTFUtils() {
  79760. }
  79761. /**
  79762. * If the uri is a base64 string
  79763. * @param uri: the uri to test
  79764. */
  79765. GLTFUtils.IsBase64 = function (uri) {
  79766. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  79767. };
  79768. /**
  79769. * Decode the base64 uri
  79770. * @param uri: the uri to decode
  79771. */
  79772. GLTFUtils.DecodeBase64 = function (uri) {
  79773. var decodedString = atob(uri.split(",")[1]);
  79774. var bufferLength = decodedString.length;
  79775. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  79776. for (var i = 0; i < bufferLength; i++) {
  79777. bufferView[i] = decodedString.charCodeAt(i);
  79778. }
  79779. return bufferView.buffer;
  79780. };
  79781. GLTFUtils.ValidateUri = function (uri) {
  79782. return (uri.indexOf("..") === -1);
  79783. };
  79784. return GLTFUtils;
  79785. }());
  79786. GLTF2.GLTFUtils = GLTFUtils;
  79787. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79788. })(BABYLON || (BABYLON = {}));
  79789. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  79790. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79791. var BABYLON;
  79792. (function (BABYLON) {
  79793. var GLTF2;
  79794. (function (GLTF2) {
  79795. var GLTFLoaderExtension = /** @class */ (function () {
  79796. function GLTFLoaderExtension() {
  79797. this.enabled = true;
  79798. }
  79799. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  79800. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  79801. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  79802. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  79803. var _this = this;
  79804. if (!property.extensions) {
  79805. return false;
  79806. }
  79807. var extension = property.extensions[this.name];
  79808. if (!extension) {
  79809. return false;
  79810. }
  79811. // Clear out the extension before executing the action to avoid recursing into the same property.
  79812. property.extensions[this.name] = undefined;
  79813. action(context + "extensions/" + this.name, extension, function () {
  79814. // Restore the extension after completing the action.
  79815. property.extensions[_this.name] = extension;
  79816. });
  79817. return true;
  79818. };
  79819. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  79820. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  79821. };
  79822. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  79823. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  79824. };
  79825. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  79826. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  79827. };
  79828. GLTFLoaderExtension._ApplyExtensions = function (action) {
  79829. var extensions = GLTFLoaderExtension._Extensions;
  79830. if (!extensions) {
  79831. return false;
  79832. }
  79833. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  79834. var extension = extensions_1[_i];
  79835. if (extension.enabled && action(extension)) {
  79836. return true;
  79837. }
  79838. }
  79839. return false;
  79840. };
  79841. //
  79842. // Utilities
  79843. //
  79844. GLTFLoaderExtension._Extensions = [];
  79845. return GLTFLoaderExtension;
  79846. }());
  79847. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  79848. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79849. })(BABYLON || (BABYLON = {}));
  79850. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  79851. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  79852. var BABYLON;
  79853. (function (BABYLON) {
  79854. var GLTF2;
  79855. (function (GLTF2) {
  79856. var Extensions;
  79857. (function (Extensions) {
  79858. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  79859. var MSFTLOD = /** @class */ (function (_super) {
  79860. __extends(MSFTLOD, _super);
  79861. function MSFTLOD() {
  79862. return _super !== null && _super.apply(this, arguments) || this;
  79863. }
  79864. Object.defineProperty(MSFTLOD.prototype, "name", {
  79865. get: function () {
  79866. return "MSFT_lod";
  79867. },
  79868. enumerable: true,
  79869. configurable: true
  79870. });
  79871. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  79872. return this._loadExtension(context, node, function (context, extension, onComplete) {
  79873. for (var i = extension.ids.length - 1; i >= 0; i--) {
  79874. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  79875. if (!lodNode) {
  79876. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  79877. }
  79878. loader._traverseNode(context, lodNode, action, parentNode);
  79879. }
  79880. loader._traverseNode(context, node, action, parentNode);
  79881. onComplete();
  79882. });
  79883. };
  79884. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  79885. var _this = this;
  79886. return this._loadExtension(context, node, function (context, extension, onComplete) {
  79887. var nodes = [node];
  79888. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  79889. var index = _a[_i];
  79890. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  79891. if (!lodNode) {
  79892. throw new Error(context + ": Failed to find node " + index);
  79893. }
  79894. nodes.push(lodNode);
  79895. }
  79896. loader._addLoaderPendingData(node);
  79897. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  79898. loader._removeLoaderPendingData(node);
  79899. onComplete();
  79900. });
  79901. });
  79902. };
  79903. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  79904. var _this = this;
  79905. loader._whenAction(function () {
  79906. loader._loadNode(context, nodes[index]);
  79907. }, function () {
  79908. if (index !== nodes.length - 1) {
  79909. var previousNode = nodes[index + 1];
  79910. previousNode.babylonMesh.setEnabled(false);
  79911. }
  79912. if (index === 0) {
  79913. onComplete();
  79914. return;
  79915. }
  79916. setTimeout(function () {
  79917. loader._tryCatchOnError(function () {
  79918. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  79919. });
  79920. }, MSFTLOD.MinimalLODDelay);
  79921. });
  79922. };
  79923. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  79924. var _this = this;
  79925. return this._loadExtension(context, material, function (context, extension, onComplete) {
  79926. var materials = [material];
  79927. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  79928. var index = _a[_i];
  79929. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  79930. if (!lodMaterial) {
  79931. throw new Error(context + ": Failed to find material " + index);
  79932. }
  79933. materials.push(lodMaterial);
  79934. }
  79935. loader._addLoaderPendingData(material);
  79936. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  79937. loader._removeLoaderPendingData(material);
  79938. onComplete();
  79939. });
  79940. });
  79941. };
  79942. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  79943. var _this = this;
  79944. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  79945. assign(babylonMaterial, isNew);
  79946. if (index === 0) {
  79947. onComplete();
  79948. return;
  79949. }
  79950. // Load the next LOD when the loader is ready to render and
  79951. // all active material textures of the current LOD are loaded.
  79952. loader._executeWhenRenderReady(function () {
  79953. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  79954. setTimeout(function () {
  79955. loader._tryCatchOnError(function () {
  79956. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  79957. });
  79958. }, MSFTLOD.MinimalLODDelay);
  79959. });
  79960. });
  79961. });
  79962. };
  79963. /**
  79964. * Specify the minimal delay between LODs in ms (default = 250)
  79965. */
  79966. MSFTLOD.MinimalLODDelay = 250;
  79967. return MSFTLOD;
  79968. }(GLTF2.GLTFLoaderExtension));
  79969. Extensions.MSFTLOD = MSFTLOD;
  79970. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  79971. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  79972. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79973. })(BABYLON || (BABYLON = {}));
  79974. //# sourceMappingURL=MSFT_lod.js.map
  79975. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  79976. var BABYLON;
  79977. (function (BABYLON) {
  79978. var GLTF2;
  79979. (function (GLTF2) {
  79980. var Extensions;
  79981. (function (Extensions) {
  79982. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  79983. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  79984. function KHRMaterialsPbrSpecularGlossiness() {
  79985. return _super !== null && _super.apply(this, arguments) || this;
  79986. }
  79987. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  79988. get: function () {
  79989. return "KHR_materials_pbrSpecularGlossiness";
  79990. },
  79991. enumerable: true,
  79992. configurable: true
  79993. });
  79994. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  79995. var _this = this;
  79996. return this._loadExtension(context, material, function (context, extension, onComplete) {
  79997. loader._createPbrMaterial(material);
  79998. loader._loadMaterialBaseProperties(context, material);
  79999. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  80000. assign(material.babylonMaterial, true);
  80001. });
  80002. };
  80003. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  80004. var babylonMaterial = material.babylonMaterial;
  80005. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  80006. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  80007. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  80008. if (properties.diffuseTexture) {
  80009. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  80010. if (!texture) {
  80011. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  80012. }
  80013. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  80014. }
  80015. if (properties.specularGlossinessTexture) {
  80016. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  80017. if (!texture) {
  80018. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  80019. }
  80020. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  80021. babylonMaterial.reflectivityTexture.hasAlpha = true;
  80022. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  80023. }
  80024. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  80025. };
  80026. return KHRMaterialsPbrSpecularGlossiness;
  80027. }(GLTF2.GLTFLoaderExtension));
  80028. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  80029. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  80030. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  80031. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80032. })(BABYLON || (BABYLON = {}));
  80033. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  80034. (function universalModuleDefinition(root, factory) {
  80035. if (root && root["BABYLON"]) {
  80036. return;
  80037. }
  80038. if(typeof exports === 'object' && typeof module === 'object')
  80039. module.exports = factory();
  80040. else if(typeof define === 'function' && define.amd)
  80041. define([], factory);
  80042. else if(typeof exports === 'object')
  80043. exports["BABYLON"] = factory();
  80044. else {
  80045. root["BABYLON"] = factory();
  80046. }
  80047. })(this, function() {
  80048. return BABYLON;
  80049. });